SafeGetUnit (pcall example) (Full Version)

All Forums >> [New Releases from Matrix Games] >> Command: Modern Operations series >> Mods and Scenarios >> Lua Legion



Message


jkgarner -> SafeGetUnit (pcall example) (3/13/2021 11:52:43 AM)

OK,
Apparently, Lua code execute by events will terminate the event execution if there is an error, like ScenEdit_GetUnit fails...

I was seeing this on the forums, but did not pay much attention to it...to my regret, as I am now writing substantial event driven Lua code...

Since most of my events deal with a unit, I though a SafeGetUnit function might be helpful (too prevent repeatedly writing pcall, and potential errors with each instance...)

The function is provided in the attachment, along with test code that proves that the function behaves as described.

If you find it useful, use it.




Parel803 -> RE: SafeGetUnit (pcall example) (3/13/2021 1:44:04 PM)

thank you,
with regards GJ




michaelm75au -> RE: SafeGetUnit (pcall example) (3/13/2021 7:40:25 PM)

As mentioned before, most functions will return an error when they are run in the console. It is up to the user to check outcomes of function calls during events as the functions are set to run non-interactively.
If there is a specific case where the function call does not return something to test, please give me an example save file showing it to investigate.




jkgarner -> RE: SafeGetUnit (pcall example) (3/14/2021 1:22:38 AM)

OK, so a little more testing shows that a safe GetUnit is not necessary, except as instruciton on using pcall to trap errors.

The following code works for events:
Tool_EmulateNoConsole(true)
ScenEdit_AddSide({name='test'})
local u = ScenEdit_GetUnit({side='test', name='asdf'})
if(u ~= nil) then
    --print('u was defined')
    ScenEdit_MsgBox ('u was defined',1)
else
    --print('u not defined')
    ScenEdit_MsgBox ('u not defined',1)
end
ScenEdit_RemoveSide({name='test'})
Tool_EmulateNoConsole(false)
The Tool_EmulateNoCosole, sets the console to execution as though it were executing from an event, and swallows print statments and errors.

As a word of caution, you MUST check the return value of all your calls, because they may have failed, and returned nil.

Tracking down errors in event code is tedious business, as any error will terminate the script. (often without notice)

I am trying to find a way to build automated unit tests for my event code. I have not figured it out yet. If anybody has ideas on how to do that, I'd appreciate a discussion on the topic.






Page: [1]

Valid CSS!




Forum Software © ASPPlayground.NET Advanced Edition 2.4.5 ANSI
2.25