C:
#include "windows.h"
#include <iostream.h>
extern "C"{
#include "lua.h"
#include "lualib.h"
#include "lauxlib.h"
}
#pragma comment(lib,"lua5.1.lib")
lua_State * L;
static int GetRef(lua_State *L) //取引用
{
int ref = luaL_checkint(L, -1);
lua_pop(L, -1); //清栈
//根据索引取lua对象并压栈
lua_rawgeti(L, LUA_REGISTRYINDEX, ref);
if (!lua_istable(L, -1))
{
//printf("ref table is not valid:%d", ref);
//return 0;
}
return 1;
}
static int SetRef(lua_State *L) //设置引用
{
//创建索引并从栈顶弹出该对象
int ref = luaL_ref(L, LUA_REGISTRYINDEX);
if(ref == LUA_REFNIL)
{
//printf("set ref error, arg is nil");
//return 0;
}
lua_pop(L, -1); //清栈
//压入参数
lua_pushnumber(L, (lua_Number)ref);
return 1;
}
static int DelRef(lua_State *L) //删引用
{
int ref = luaL_checkint(L, -1);
lua_pop(L, -1); //清栈
luaL_unref(L, LUA_REGISTRYINDEX, ref);
return 0;
}
static const luaL_reg lengine[] = {
{"getref", GetRef},
{"setref", SetRef},
{"delref", DelRef},
{NULL, NULL},
};
int main()
{
//创建一个指向lua解释器的指针
L = luaL_newstate();
//加载lua标准库
luaL_openlibs(L);
//加载脚本
luaL_register(L, "lengine", lengine);
luaL_dofile(L,"1.lua");
lua_close(L);
return 0;
}
lua:
local a = {1,2,3}
local ref = lengine.setref(a)
local b = lengine.getref(ref)
print(a == b and "true\n" or "false\n")
lengine.delref(ref)
local b = lengine.getref(ref)
print(a == b and "true\n" or "false\n")