Calling C functions from Lua
All of the code that we have written so far has been about exposing C to Lua using Lua Bridge. Any C function exposed through Lua Bridge can be called from Lua. If a function is in a namespace and not a class, it is called with the dot syntax: Math.Sqrt(16)
. But, if a function is in a class, it needs to be called with the colon syntax: vector:Normalize()
. The following code shows how to expose a C function to Lua and how to call it from Lua.
The C code needs to declare the appropriate vector 3 class, a Normalize
member function, and a global dot
product function. Next, the Register
function exposes all of these functions to Lua, using Lua Bridge:
class Vec3 { public: float x, y, z; float Normalize() { float dot = x * x + y * y + z * z; if (dot == 0) { return 0; } return sqrt(dot); } } float Dot(Vec3 a, Vec3 b) { return a.x * b.x + a.y * b.y + a.z * b.z; } void Register(lua_State* L) { getGlobalNamespace...