Last active
October 21, 2019 11:23
-
-
Save ggzeng/66663976fd42ecb57514d3a5fb92e6ff to your computer and use it in GitHub Desktop.
在clang中调用lua函数
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
function f(x, y) | |
return x + y | |
end |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include <stdio.h> | |
#include <string.h> | |
#include "lua.h" | |
#include "lauxlib.h" | |
#include "lualib.h" | |
/* call a function 'f' defined in Lua */ | |
int f(lua_State *L, int x, int y) { | |
int isnum; | |
int z; | |
/* push functions and arguments */ | |
lua_getglobal(L, "f"); /* function to be called */ | |
lua_pushnumber(L, x); /* push 1st argument */ | |
lua_pushnumber(L, y); /* push 2nd argument */ | |
/* do the call (2 arguments, 1 result) */ | |
if (lua_pcall(L, 2, 1, 0) != LUA_OK) | |
error(L, "error running function 'f': %s", | |
lua_tostring(L, -1)); | |
/* retrieve result */ | |
z = lua_tointeger(L, -1); | |
lua_pop(L, 1); /* pop returned value */ | |
return z; | |
} | |
int main(void) { | |
int error; | |
int rt; | |
lua_State *L = luaL_newstate(); /* opens Lua */ | |
luaL_openlibs(L); /* opens the standard libraries */ | |
if (luaL_dofile(L, "add.lua")) { // 加载lua脚本 | |
printf("Could not load file: %sn", lua_tostring(L, -1)); | |
lua_close(L); | |
return 0; | |
} | |
rt = f(L, 2, 3); | |
printf("return val: %d\n", rt); | |
lua_close(L); | |
return 0; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment