上代码
function tellme() io.write("This is coming from lua.tellme.\n") end function square(n) io.write("Within callfuncscript.lua fcn square, arg=") io.write(tostring(n)) n = n * n io.write(", square=") io.write(tostring(n)) print(".") return(n) end print("Priming run")
C代码
#include "lauxlib.h" /* Always include this when calling Lua */ #include "lualib.h" /* Prototype for luaL_openlibs(), */ /* always include this when calling Lua */ #include "stdlib.h" /* For function exit() */ #include "stdio.h" /* For input/output */ void bail(lua_State *L, char *msg){ fprintf(stderr, "\nFATAL ERROR:\n %s: %s\n\n", msg, lua_tostring(L, -1)); exit(1); } int main(void) { lua_State *L; L = luaL_newstate(); /* Create Lua state variable */ luaL_openlibs(L); /* Load Lua libraries */ if (luaL_loadfile(L, "callfuncscript.lua")) /* Load but don't run the Lua script */ bail(L, "luaL_loadfile() failed"); /* Error out if file can't be read */ if (lua_pcall(L, 0, 0, 0)) /* PRIMING RUN. FORGET THIS AND YOU'RE TOAST */ bail(L, "lua_pcall() failed"); /* Error out if Lua file has an error */ printf("In C, calling Lua->tellme()\n"); lua_getglobal(L, "tellme"); /* Tell it to run callfuncscript.lua->tellme() */ if (lua_pcall(L, 0, 0, 0)) /* Run the function */ bail(L, "lua_pcall() failed"); /* Error out if Lua file has an error */ printf("Back in C again\n"); printf("In C, calling Lua->square(6)\n"); lua_getglobal(L, "square"); /* Tell it to run callfuncscript.lua->square() */ lua_pushnumber(L, 6); /* Submit 6 as the argument to square() */ if (lua_pcall(L, 1, 1, 0)) /* Run function, !!! NRETURN=1 !!! */ bail(L, "lua_pcall() failed"); printf("Back in C again\n"); int mynumber = lua_tonumber(L, -1); printf("Returned number=%d\n", mynumber); lua_close(L); /* Clean up, free the Lua state var */ return 0; }
本站的文章和资源来自互联网或者站长的原创,按照 CC BY -NC -SA 3.0 CN协议发布和共享,转载或引用本站文章应遵循相同协议。如果有侵犯版权的资 源请尽快联系站长,我们会在24h内删除有争议的资源。欢迎大家多多交流,期待共同学习进步。