C#: Assign Values To Lua Script
Use Case
Your C# script needs to expose values to the Lua script before it even runs its Awake()
function.
C# Implementation
The OnBeforeScriptAwake()
method, when overridden in your LunyScript
subclass, runs just before the script’s Awake()
function. Use it to assign values to the Lua script:
protected override void OnBeforeScriptAwake()
{
SetFloat(nameof(m_StartingHealth).Substring(2), m_StartingHealth);
SetObject(nameof(m_Slider).Substring(2), new LunyUISlider(m_Slider));
SetBool(nameof(m_IsDead).Substring(2), m_IsDead);
SetInt(nameof(PlayerNumber), PlayerNumber);
}
Lua Usage
You can now use any of the variables in the script’s functions, including Awake
:
function script.Awake()
print("Player #", script.PlayerNumber)
Slider.value = script.StartingHealth
end
Example
The above example was taken from LunyTankHealth.cs script.
The values are being used in the accompanying LunyTankHealth.lua script.
Limitations
These values are not currently available outside of Lua script functions in Luny 0.6:
local script = {...}
print(script.PlayerNumber) -- prints: "nil"
return script
The {...}
are actually reserved for the purpose of overcoming this limitation in a future update of Luny.
Notes
I use Substring(2)
in order to get rid of the m_
prefix of some member variables. This is purely cosmetic.
Prefer to use nameof(SomeType)
rather than hardcoding the identifier as string.
Programmers very often refactor-rename types and identifiers. The IDE will automatically rename identifiers in
nameof()
so the Lua variable name will also be updated. If however you had been using a string, the IDE won’t change the string causing identifiers in C# and Lua scripts to differ.