組み込みのサンプル

ちょっとしたサンプル。2chの書き込みから。

#include <stdio.h>

#include "lua.h"
#include "lualib.h"
#include "lauxlib.h"

int main() {
  lua_State *L = lua_open();
  luaL_loadstring(L,"function f(x, y) return x + y end");
  lua_call(L, 0, 0);
  lua_getglobal(L, "f");
  lua_pushnumber(L, 1);
  lua_pushnumber(L, 2);

  if(lua_pcall(L, 2, 1, 0) != 0) {
    printf("error: %s\n", lua_tostring(L, -1));
  } else {
    printf("%f\n", lua_tonumber(L, -1));
  }

  lua_pop(L, 1);
  lua_close(L);
}

VS2005にてコンパイル。