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);
}
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 :
Online compilers:
Luac Compiler : http://www.lua.org/manual/4.0/luac.html
click here for Memory Management in C plus plus
No comments:
Post a Comment