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(L)
.beginNamespace("Math")
.beginClass<Vec3>("Vec3")
.addData("x", &Vec3::x)
.addData("y", &Vec3::y)
.addData("z", &Vec3::z)
.addFunction("Normalize", &Vec3::Normalize)
.endClass()
.addFunction("Dot", Dot)
.endNameSpace();
}

The Lua file can create new vectors, and can then set the x, y, or z members of each vector. Then, the Dot and Normalize functions can be called. The following code sample does this:

local a = Math.Vec3()
local b = Math.Vec3()

a.x = 7
b.x = 3

print ("Dot: " .. Dot(a, b));

print ("Normalize both");
a:Normalize()
b:Normalize()

print ("Dot: " .. Dot(a, b));
..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.188.178.181