Page 1 of 1

SafeGetUnit (pcall example)

Posted: Sat Mar 13, 2021 9:52 am
by jkgarner
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.

RE: SafeGetUnit (pcall example)

Posted: Sat Mar 13, 2021 11:44 am
by Parel803
thank you,
with regards GJ

RE: SafeGetUnit (pcall example)

Posted: Sat Mar 13, 2021 5:40 pm
by michaelm75au
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.

RE: SafeGetUnit (pcall example)

Posted: Sat Mar 13, 2021 11:22 pm
by jkgarner
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:

Code: Select all

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.