extern "C"
{
#include <lua.h>
#include <lauxlib.h>
#include <lualib.h>
}
void load(char *filename , int *width , int *height )
{
lua_State *L = lua_open();
luaopen_base(L);
luaL_openlibs(L);
//luaopen_table(L);
//luaopen_io(L);
//luaopen_string(L);
//luaopen_math(L);
if(luaL_loadfile(L ,filename) || lua_pcall(L , 0 , 0 , 0) )
//error(L, "cannot run configuration file: %s",lua_tostring(L, -1));
return ;
lua_getglobal(L,"width");
lua_getglobal(L,"height");
if( !lua_isnumber(L,-2))
//error(L,"Width should be a number\n");
return ;
if(!lua_isnumber(L ,-1))
//error(L,"height should be a number \n");
return ;
*width = (int)lua_tonumber(L,-2);
*height = (int)lua_tonumber(L,-1);
lua_close(L);
}
void main()
{
int a = 1;
int *width = 0 ;
int *height = &a ;
load("test.lua" , width , height);
{
#include <lua.h>
#include <lauxlib.h>
#include <lualib.h>
}
void load(char *filename , int *width , int *height )
{
lua_State *L = lua_open();
luaopen_base(L);
luaL_openlibs(L);
//luaopen_table(L);
//luaopen_io(L);
//luaopen_string(L);
//luaopen_math(L);
if(luaL_loadfile(L ,filename) || lua_pcall(L , 0 , 0 , 0) )
//error(L, "cannot run configuration file: %s",lua_tostring(L, -1));
return ;
lua_getglobal(L,"width");
lua_getglobal(L,"height");
if( !lua_isnumber(L,-2))
//error(L,"Width should be a number\n");
return ;
if(!lua_isnumber(L ,-1))
//error(L,"height should be a number \n");
return ;
*width = (int)lua_tonumber(L,-2);
*height = (int)lua_tonumber(L,-1);
lua_close(L);
}
void main()
{
int a = 1;
int *width = 0 ;
int *height = &a ;
load("test.lua" , width , height);
}
test.lua 配置
width = 100
height = 100
///实例二
extern "C"
{
#include <lua.h>
#include <lauxlib.h>
#include <lualib.h>
}
lua_State *L;
int luaAdd( int x , int y )
{
int sum;
lua_getglobal( L , "add" );
lua_pushnumber(L , x );
lua_pushnumber(L ,y );
lua_call(L ,2 , 1);
sum = (int)lua_tonumber(L ,-1);
lua_pop(L ,-1);
return sum;
}
int main(int argc , char* argv[] )
{
int sum = 0;
L = lua_open();
luaopen_base(L);
luaL_openlibs(L);
luaL_loadfile(L,"add.lua");
lua_pcall(L,0,LUA_MULTRET , 0);
sum = luaAdd(10,15);
printf("The sum is %d\n" ,sum);
lua_close(L);
return 0;
}
add.lua配置 必须放置与工程目录 .cpp文件同一个文件夹里面
2 function add(x, y) 3 return x + y 4 end