Lua-LuaCOB
Lua is small, embedded, highly dynamic programming language, which has been integrated into Spring.
Introduction
To use Lua code in your BOS/COB files, you must:
- create a mod-level directory LuaCOB/,
- make a LuaCOB/main.lua file.
Any additional files need to be included with a
include("LuaCOB/additional_file.lua" [, fenvTable])
If you don't know what a fenvTable is, don't worry, you probably don't need it anyway. More information can be found on the Lua site. It it highly recommended to read the manual and the tutorials found there. Note that Spring's Lua version is 5.0.3, so please take note which version of the manual you're reading.
Intefacing COB->Lua
All Lua functions that are called by COB are given three parameters:
- unitID - ID of the unit calling the function,
- unitDefID - ID of the unitDef,
- teamID - self-explanatory.
You can call scripts with any (enough for all practical purpouses) amount of additional arguments.
Example functions:
function GetNearestEnemy(unitID, unitDefID, teamID, radius)
local px, py, pz = Sim.GetUnitPosition(unitID)
if (px == nil) then
return
end
local nearDist = 1.0e20
local nearUnit
local units = Sim.GetUnitsInCylinder(px, pz, radius)
for _,enemyID in ipairs(units) do
if (not Sim.IsUnitAllied(enemyID)) then
local ex, ey, ez = Sim.GetUnitPosition(enemyID)
if (ex ~= nil) then
local dx, dy, dz = (px - ex), (py - ey), (pz - ez)
local dist = (dx * dx) + (dy * dy) + (dz + dz)
if (dist < nearDist) then
nearUnit = enemyID
nearDist = dist
end
end
end
end
if (nearUnit == nil) then
return -1
else
return nearUnit
end
end
Please note that returning tables doesn't currently work as one could expect. (Description what it does here) If you want to return multiple values from a table, you need to do it like this:
function ReturnSomeValues(u, ud, t, ...)
return arg[1], arg[2], arg[3] -- instead of arg
end
Calling Lua from BOS
To call a Lua function from BOS code, you need to declare it first:
// BOS
lua_MyFunction() { return 0; }
Then just call this script. The lua_ prefix does its magic and routes the call to Lua code instead of calling the usual BOS code. Note that arguments don't matter, they are passed anyway:
call-script lua_MyFunction(arg1, arg2);
Summary
Steps needed to call a Lua function in a BOS call-script call:
- define a Lua function MyFunction(unitID, unitDefID, teamID, ...) in LuaCOB/main.lua or a file included by it
- define a BOS/COB script lua_MyFunction() { return 0; } so the compiler knows about it
- call your function with call-script lua_MyFunction()
- return values can be found in get LUA1..9
- get LUA0 returns 1 when call was successful (regardless of its return values) and 0 in case of failure.
Interfacing Lua->COB
Lua:
Sim.COBScript(unitID, "CustomScript", arg1, arg2, arg3)
COB:
CustomScript(arg1, arg2, arg3) { ... }