SafeGetUnit (pcall example)

All discussions & material related to Command's Lua interface

Moderators: angster, RoryAndersonCDT, michaelm75au, MOD_Command

Post Reply
jkgarner
Posts: 175
Joined: Thu Apr 30, 2020 12:42 pm

SafeGetUnit (pcall example)

Post 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.
Attachments
SafeGetUnit.txt
(7.03 KiB) Downloaded 20 times
Parel803
Posts: 941
Joined: Thu Oct 10, 2019 3:39 pm
Location: Netherlands

RE: SafeGetUnit (pcall example)

Post by Parel803 »

thank you,
with regards GJ
User avatar
michaelm75au
Posts: 12457
Joined: Sat May 05, 2001 8:00 am
Location: Melbourne, Australia

RE: SafeGetUnit (pcall example)

Post 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.
Michael
jkgarner
Posts: 175
Joined: Thu Apr 30, 2020 12:42 pm

RE: SafeGetUnit (pcall example)

Post 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.


Post Reply

Return to “Lua Legion”