YoggieEngine/SandboxApplication/hello.cpp
2021-09-29 19:14:27 +01:00

70 lines
1.9 KiB
C++

#include <stdio.h>
#include <lua.h>
extern "c" {
static int l_cppfunction(lua_State *L) {
double arg = luaL_checknumber(L,1);
lua_pushnumber(L, arg * 0.5);
return 1;
}
}
int main (int argc, char *argv[] ){
printf("Test lua embedding");
printf("init lua");
lua_State *L;
L = luaL_newState();
printf("Load the (optional) standard libraries, to have to print function");
luaL_openLibs(L);
printf("Load chenk. without executing it.");
if( luaL_loadfile(L, "hello.lua")){
printf("Something went wrong loading the check (syntax error?)");
printf(lua_tostring(L, -1));
lua_pop(L,1);
}
printf("Make a insert a global var into lua from C++");
lua_pushnumber(L, 1.1);
lua_setglobal(L, "cppvar");
printf("Execute the Lua chunk");
if(lua_pcall(L, 0, LUA_MULTRET, 0)){
printf("Something went wrong during execution");
printf(lua_tostring(L, -1));
lua_pop(L,1);
}
printf("read a global var from lua into C++");
lua_getglobal(L, "luavar");
double luavar = lua_tonumber(L, -1);
lua_pop(L,1);
printf("c++ can read the value set from lua luavar = %s", luavar );
printf("execute a lua function from cpp");
lua_getglobal(L, "myluafunction");
lua_pushnumber(L, 5);
lua_pcall(L,1,1,0);
printf("the return value of the function was %s", lua_tostring(L, -1));
lua_pop(L,1);
printf("execute a cpp function from lua");
printf("first register the function in lua");
lua_pushcfunction(L , l_cppfunction);
lua_setglobal(L, "cppfunction");
printf("Call a lua function that uses the cpp function");
lua_setglobal(L, "myFunction");
lua_pushnumber(L, 5);
lua_pcall(L,1,1,0);
printf("the return value of the function was %s", lua_tonumber(L,-1));
lua_pop(L,1);
printf("Release the lua environment");
lua_close(L);
}