ggzeng
10/17/2019 - 12:59 PM

call lua function from clang

在clang中调用lua函数

#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;
}
function f(x, y)
  return x + y
end