标签:
//test.c #include <stdio.h> #include "lua.h" #include "lualib.h" #include "lauxlib.h" #include <stdlib.h> lua_State *L; int main(){ L = luaL_newstate();//创建state以及加载标准库 luaL_openlibs(L);//打开所有lua标准库加入到已经创建的state luaL_loadfile(L,"1.lua");//加载lua文件 lua_pcall(L,0,0,0);//相当于把整个lua文件的内容当成一个function来执行 lua_getglobal(L,"lua_value");//从lua变量空间中将全局变量lua_value读取出来放入虚拟堆栈中 int value = (int)lua_tonumber(L,-1);//从虚拟堆栈中读取刚才压入的变量,-1表示读取堆栈最顶端的元素 printf("%d\n",value); return 0; }
//1.lua lua_value = 100; print "hello lua";
例子2:
//例子2 test.c 1 #include <stdio.h> 2 #include "lua.h" 3 #include "lualib.h" 4 #include "lauxlib.h" 5 #include <stdlib.h> 6 7 lua_State* L; 8 int add(lua_State* L){ 9 10 int x = luaL_checkint(L,1); 11 12 int y = luaL_checkint(L,2); 13 14 printf("result:%d\n",x+y); 15 16 return 1; 17 } 18 19 int main(int argc, char *argv[]) 20 { 21 L = luaL_newstate(); 22 23 luaL_openlibs(L); 24 25 //lua_pushcfunction(L, add); 26 27 //lua_setglobal(L, "ADD"); 28 //从堆栈上弹出一个值,并将其设置到对应的全局变量“ADD”中 29 //它由一个宏定义出来:#define lua_setglobal(L,s) lua_setfield(L,LUA_GLOBALSINDEX,s) 30 31 lua_register(L,"ADD",add); 32 33 if (luaL_loadfile(L,"mylua.lua")){ 34 printf("error\n"); 35 } 36 37 lua_pcall(L,0,0,0); 38 39 printf("----------------------"); 40 41 lua_getglobal(L, "mylua"); 42 43 lua_pcall(L,0,0,0); 44 45 printf("hello my lua\n"); 46 return 0; 47 }
//mylua.lua 1 function mylua() 2 3 ADD(1,2) 4 ADD(3,4); 5 6 end 7 8 9 function hello() 10 11 print "hello lua and c"; 12 13 end
标签:
原文地址:http://www.cnblogs.com/program-framework/p/4484637.html