#include <stdio.h>
#include <string.h>
#include <lua.h>
#include <lauxlib.h>
#include <lualib.h>
static int say_hello(lua_State *L)
{
const char *s = lua_tostring(L,1);
printf("hell,%s\n",s);
return 0;
}
int main(void)
{
lua_State *L = luaL_newstate();;
luaL_openlibs(L);
//写入全局变量
lua_pushnumber( L, 211 );
lua_setglobal( L, "hp" );
//lua_pop(L,2);
//读取全局变量
lua_getglobal( L, "hp" );
int res = lua_tointeger(L, -1);
printf("%d\n",res);
lua_pop(L,1);
//设置一个有名称的table
lua_newtable(L);
lua_pushinteger(L, 10025);
lua_setfield(L, 1, "id");
lua_pushinteger(L, 3);
lua_setfield(L, 1, "good_count");
lua_pushinteger(L, 100);
lua_setfield(L, 1, "count");
lua_pushinteger(L, 15);
lua_setfield(L, 1, "outlet_count");
lua_setglobal(L,"customer_table");
//读取table中的值
int result;
lua_getglobal(L,"customer_table");
lua_pushstring(L,"count");
lua_gettable(L,-2);
result = lua_tointeger(L,-1);
printf("%d\n",result);
lua_pop(L,1);
lua_pushstring(L,"outlet_count");
lua_gettable(L,-2);
result = lua_tointeger(L,-1);
printf("%d\n",result);
lua_pop(L,1);
//函数相互调用
lua_register(L,"say_hello",say_hello);
const char* dosomething = " \
function dosomething(words)\
say_hello(words) \
end \
";
luaL_dostring(L,dosomething);
lua_getglobal(L, "dosomething");
lua_pushstring(L,"yexuqiang");
res = lua_pcall(L, 1, 1,0);
printf("res:%d\n",res);
lua_close(L);
return 0;
}
|
请发表评论