Page 1 of 1
[solved]using lua with c++
Posted: Mon Apr 26, 2010 2:36 pm
by cndr
I am new to lua, and I would like to make lua change variables in c++, say I have something like the following code, the hardest thing I have learning lua, is integrating it into c++.
Code: Select all
extern "C"
{
#include "lua.h"
#include "lualib.h"
#include "lauxlib.h"
}
int main()
{
int s = 0;
int x;
lua_State *L = lua_open();
luaL_openlibs(L);
luaL_dofile(L,"file.lua"); // lua would set x to 5
printf("x is %d .",x); //how would I get lua to set x?
lua_close(L);
return 0;
}
Re: using lua with c++
Posted: Mon Apr 26, 2010 2:56 pm
by mv2112
There are a few ways you could do this but here i think is the easiest.
Code: Select all
extern "C"
{
#include "lua.h"
#include "lualib.h"
#include "lauxlib.h"
}
int main()
{
int s = 0;
int x;
lua_State *L = lua_open();
luaL_openlibs(L);
luaL_dofile(L,"file.lua"); // lua would set x to 5
x=lua_getglobal(L,"x"); //assuming the variable in the lua script is also named x
printf("x is %d .",x); //how would I get lua to set x?
lua_close(L);
return 0;
}
You could also register a SetX function to lua but X would have to be global.
Re: using lua with c++
Posted: Mon Apr 26, 2010 3:13 pm
by cndr
didn't work for me, maybe I should just stick with pure lua for a while, it seems getting the code to work with c++ is harder than I thought, when I ran the code I got the following error message:
Code: Select all
error: void value not ignored as it ought to be
the lua file just had
Re: using lua with c++
Posted: Mon Apr 26, 2010 3:37 pm
by mv2112
Oops, my code was wrong, this works, i tested it:
Code: Select all
extern "C"
{
#include "lua.h"
#include "lualib.h"
#include "lauxlib.h"
}
int main()
{
int s = 0;
int x;
lua_State *L = lua_open();
luaL_openlibs(L);
luaL_dofile(L,"file.lua"); // lua would set x to 5
lua_getglobal(L,"x"); //assuming the variable in the lua script is also named x
x=lua_tonumber(L,-1); //gets x from the lua stack
printf("x is %d .",x);
lua_close(L);
return 0;
}
Re: using lua with c++
Posted: Mon Apr 26, 2010 5:09 pm
by cndr
Thanks for the help I really appreciate it