extern "C"{ #include "lua.h" #include "lualib.h" #include "lauxlib.h" } #define err_return(num,fmt,args...) do{printf("[%s:%d]"fmt"\n",__FILE__,__LINE__,##args);return(num);} while(0) #define err_exit(num,fmt,args...) do{printf("[%s:%d]"fmt"\n",__FILE__,__LINE__,##args);exit(num);} while(0) using namespace std; int csum(lua_State* l) { int a = lua_tointeger(l,1) ; int b = lua_tointeger(l,2) ; lua_pushinteger(l,a+b) ; return 1 ; } int main() { lua_State* luaState = luaL_newstate() ; //創建lua運行環境 if (luaState == NULL) err_return(-1,"luaL_newstat() failed"); int ret = 0 ; ret = luaL_loadfile(luaState,"func.lua") ; //加載lua腳本文件 if (ret != 0) err_return(-1,"luaL_loadfile failed") ; ret = lua_pcall(luaState,0,0,0) ; if (ret != 0) err_return(-1,"lua_pcall failed:%s",lua_tostring(luaState,-1)) ; //---------------------------------------------------------------------------------------- lua_getglobal(luaState,"width"); //-2 //獲取lua中定義的變量 lua_getglobal(luaState,"height"); //-1 printf("height:%ld width:%ld\n",lua_tointeger(luaState,-1),lua_tointeger(luaState,-2)) ; lua_pop(luaState,1) ; //恢復lua的棧 //---------------------------------------------------------------------------------------- int a = 11 ; int b = 12 ; lua_getglobal(luaState,"sub"); //調用lua中的函數sub lua_pushinteger(luaState,a) ; lua_pushinteger(luaState,b) ; ret = lua_pcall(luaState,2,1,0) ; //a-b if ( ret != 0 ) err_return(-1,"lua_pcall failed:%s",lua_tostring(luaState,-1)) ; printf("sum:%d - %d = %ld\n",a,b,lua_tointeger(luaState,-1)) ; lua_pop(luaState,1) ; //---------------------------------------------------------------------------------------- const char str1[] = "hello" ; const char str2[] = "world" ; lua_getglobal(luaState,"mystrcat"); //調用lua中的函數mystrcat lua_pushstring(luaState,str1) ; lua_pushstring(luaState,str2) ; ret = lua_pcall(luaState,2,1,0) ; if ( ret != 0 ) err_return(-1,"lua_pcall failed:%s",lua_tostring(luaState,-1)) ; printf("mystrcat:%s%s = %s\n",str1,str2,lua_tostring(luaState,-1)) ; lua_pop(luaState,1) ; //---------------------------------------------------------------------------------------- lua_pushcfunction(luaState,csum) ; //註冊在lua中使用的c函數 lua_setglobal(luaState,"csum") ; //綁定到lua中的名字csum lua_getglobal(luaState,"mysum"); //調用lua中的mysum函數,該函數調用本程序中定義的csum函數實現加法 lua_pushinteger(luaState,a) ; lua_pushinteger(luaState,b) ; ret = lua_pcall(luaState,2,1,0) ; if ( ret != 0 ) err_return(-1,"lua_pcall failed:%s",lua_tostring(luaState,-1)) ; printf("mysum:%d + %d = %ld\n",a,b,lua_tointeger(luaState,-1)) ; lua_pop(luaState,1) ; lua_close(luaState) ; //釋放lua運行環境 return 0 ; }
func.lua
--變量定義 width=1 ; height=2 ; --lua函數定義,實現減法 function sub(a,b) return a-b ; end --lua函數定義,實現字符串相加 function mystrcat(a,b) return a..b ; end --lua函數定義,通過調用c代碼中的csum函數實現加法 function mysum(a,b) return csum(a,b) ; end
沒有留言:
張貼留言