关于C存储,取得,释放lua的引用

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")


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值