Technology Quotes

One machine can do the work of fifty ordinary men. No machine can do the work of one extraordinary man - Elbert Hubbard

Calling Lua Function From C Program

            Lua is an embedded  language and its library can be linked with other languages also, which makes it very powerful language. C API is a set of functions , that allow the application to interact with Lua.
Lua is an Extended language because we can define functionality in lua script, that can be called through application.
Lua is an extensible language that means we can extend lua library by defining our own functions. All functions defined shall be in ANSI C.
Lua function can be called through Application; C functions can also be called from Lua script.

Stack:
Communication between Lua and C happens with the help of a stack. As we know stack follows (LIFO) Last in First out Rule, so communication between lua and C includes both Pushing and popping functionality.

 



 
Lets say we have a Lua script named MyLua.Lua which has a function MyLuaFunction, that takes one argument and returns its square.
            function MyLuaFunction(x)
                        Print(“In MyLua Function”)
                        return x*x
            end
we can call this function through our C code with following method :
            #include”lua.hpp”
            #include<iostream>
Lua_state *L;
            Int main() {
                        L = lua_open(); // To Create Empty Lua Enviourment
                        luaL_openLibs(L); // TO include standard Lua Libraries in the state/enviourmrnt
                        luaL_dofile(“MyLua.Lua”); // Loads and runs the given file.
                        lua_getglobal(L,“MyLuaFunction”); //Push MyLuaFunction into stack
                        lua_pushnumber(5); // Pushes argument 5 into stack
                        lua_call(L,1,1); Commad/ API to tell Lua to execute function
                        Int sqr = lua_tonumber(L,-1);
printf(“Square  = %d ”, sqr);
lua_close(L);
}
 void lua_call (lua_State *L, int nargs, int nresults);
1st Argument is Lua State .
2nd Argument is no. of arguments which we have pushed into stack .
3rd argument is no. of results/ returning values which Lua function will be returning .


Links :

No comments:

Post a Comment