Lua sync to unsync
From Spring
synced and unsynced lua
When making a gadget you will sometimes want to combine synced and unsynced code.
For example if you do some things with units, that code will need to be synced.
The UnitDestroyed, UnitFinished etc. callins can only be called in synced code. Using them inside unsynced code is not going to work.
If you want to draw on the screen (for example to mark units) then the drawing will have to happen in unsynced code.
The following example demonstrates how to change the value inside the synced block of code and read the value in the unsynced block of code:
if (gadgetHandler:IsSyncedCode()) then
--SYNCED CODE
local number = 10 -- declaring local variable 'number'
function gadget:SomeSyncedCallin(...)
number=number+1 -- increment variable's value by one
_G.number=number -- save the new value into a global variable
end
else
--UNSYNCED CODE
function gadget:SomeUnsyncedCallin(...)
Spring.Echo(SYNCED.number) -- print the global variable's value on screen
end
end
Another way is to use the SendToUnsynced callin.
Here is an example by quantum:
http://pastebin.com/hMHv3Lrf
[LCC]quantum[0K] every time there is a new target, i send "addTarget" and its number to unsynced
[LCC]quantum[0K] when a target is removed from the list, i send "removeTarget" and its number
[LCC]quantum[0K] this wierd stuff:
[LCC]quantum[0K] _G.laserEventArgs = eventArgs
[LCC]quantum[0K] SendToUnsynced("LaserEvent")
[LCC]quantum[0K] _G.laserEventArgs = nil
[LCC]quantum[0K] puts the eventArgs table somewhere were unsynced can find it
[LCC]quantum[0K] sends a signal to unsynced called "LaserEvent"
[LCC]quantum[0K] and removes the table
[LCC]quantum[0K] on the unsynced side, _G.laserEventArgs becomes SYNCED.laserEventArgs
[LCC]quantum[0K] this copies it to another table, ready for reuse: for k, v in spairs(SYNCED.laserEventArgs) do
[LCC]quantum[0K] eventArgs[k] = v
[LCC]quantum[0K] end
[LCC]quantum[0K] also, this: gadgetHandler:AddSyncAction("LaserEvent", HandleLaserEvent)
LCC]quantum[0K] means that i want the HandleLaserEvent function to be called every time i do SendToUnsynced("LaserEvent")