lua luaL_ref引用

本文深入探讨了Lua编程中luaL_ref和luaL_unref两个关键函数的功能,解释了如何在栈操作中创建和管理对象引用,通过实例展示了这些函数在实际应用中的使用方法。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

介绍

int luaL_ref (lua_State *L, int t);
Creates and returns a reference, in the table at index t, for the object at the top of the stack (and pops the object)….
You can retrieve an object referred by reference r by calling lua_rawgeti(L, t, r). Function luaL_unref frees a reference and its associated object.
在当前栈索引t处的元素是一个table, 在该table中创建一个对象, 对象是当前栈顶的元素, 并返回创建对象在表中的索引值, 之后会pop栈顶的对象; (即将栈顶元素放到t对应的table中)

源码

freelist是值为0的宏, 所以可以任务总是将t的第0个值存放了下一个空闲位置的坐标;
空闲位置通过相互连接得到一个freelist: ref = t[freelist] 存放的是上一个之前被unref的元素的位置, 而 t[ref] 则是存放上上个unref的元素位置, 这样的连接方式就形成了freelist, 以便快速查找;

LUALIB_API int luaL_ref (lua_State *L, int t) {
  int ref;
  if (lua_isnil(L, -1)) {
    lua_pop(L, 1);  /* remove from stack */
    return LUA_REFNIL;  /* 'nil' has a unique fixed reference */
  }
  t = lua_absindex(L, t);
  lua_rawgeti(L, t, freelist);  /* get first free element   当前freelist保存了一个空闲元素位置 */
  ref = (int)lua_tointeger(L, -1);  /* ref = t[freelist]   */    
  lua_pop(L, 1);  /* remove it from stack */
    //下面两步就是将当前freelist指向的ref位置的元素从freelist中删除, 
    //  同时将上上个被unref的元素位置放到freelist中;
    lua_rawgeti(L, t, ref);  /* remove it from list         t[ref] 存放的是上上个被unref的元素 */     
    lua_rawseti(L, t, freelist);  /* (t[freelist] = t[ref]) */
  }
  else  /* no free elements */
    ref = (int)lua_rawlen(L, t) + 1;  /* get a new reference */
  lua_rawseti(L, t, ref);   // 将栈顶元素设置到t[ref]
  return ref;
}

下面看unref的函数源码:

LUALIB_API void luaL_unref (lua_State *L, int t, int ref) {
  if (ref >= 0) {
    t = lua_absindex(L, t);
    lua_rawgeti(L, t, freelist);
    lua_rawseti(L, t, ref);  /* t[ref] = t[freelist]   类似将unref的位置插入链表头 */   
    lua_pushinteger(L, ref);
    lua_rawseti(L, t, freelist);  /* t[freelist] = ref */
  }
}

示例

可以用一个简单的例子来演示luaL_ref的用法:

// main.lua中有个全局函数
function gf()
  print("hello world")
end
// c++中处理
void callgf()
{
  lua_getglobal(L,"gf");
  // 存放函数到注册表中并返回引用
  int ref =  luaL_ref(L,LUA_REGISTRYINDEX);
  // 从注册表中读取该函数并调用
  lua_rawgeti(L,LUA_REGISTRYINDEX,ref);
  lua_pcall(L,0,0,0);
}

上面的函数会调用gf打印出”hello world”

/* * Tencent is pleased to support the open source community by making xLua available. * Copyright (C) 2016 THL A29 Limited, a Tencent company. All rights reserved. * Licensed under the MIT License (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at * http://opensource.org/licenses/MIT * Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ #if USE_UNI_LUA using LuaAPI = UniLua.Lua; using RealStatePtr = UniLua.ILuaState; using LuaCSFunction = UniLua.CSharpFunctionDelegate; #else using LuaAPI = XLua.LuaDLL.Lua; using RealStatePtr = System.IntPtr; using LuaCSFunction = XLua.LuaDLL.lua_CSFunction; #endif namespace XLua { using System; using System.Collections.Generic; public class LuaEnv : IDisposable { internal RealStatePtr L; private LuaTable _G; internal ObjectTranslator translator; internal int errorFuncRef = -1; #if THREAD_SAFT || HOTFIX_ENABLE internal object luaEnvLock = new object(); #endif public LuaEnv() { #if THREAD_SAFT || HOTFIX_ENABLE lock(luaEnvLock) { #endif LuaIndexes.LUA_REGISTRYINDEX = LuaAPI.xlua_get_registry_index(); ; // Create State L = LuaAPI.luaL_newstate(); //Init Base Libs LuaAPI.luaopen_xlua(L); LuaAPI.luaopen_i64lib(L); LuaAPI.luaopen_perflib(L); translator = new ObjectTranslator(this, L); translator.createFunctionMetatable(L); translator.OpenLib(L); ObjectTranslatorPool.Instance.Add(L, translator); LuaAPI.lua_atpanic(L, StaticLuaCallbacks.Panic); LuaAPI.lua_pushstdcallcfunction(L, StaticLuaCallbacks.Print); LuaAPI.lua_setglobal(L, "print"); //template engine lib register TemplateEngine.LuaTemplate.OpenLib(L); AddSearcher(StaticLuaCallbacks.LoadBuiltinLib, 2); // just after the preload searcher AddSearcher(StaticLuaCallbacks.LoadFromCustomLoaders, 3); AddSearcher(StaticLuaCallbacks.LoadFromResource, 4); AddSearcher(StaticLuaCallbacks.LoadFromStreamingAssetsPath, -1); DoString(init_xlua, "Init"); init_xlua = null; AddBuildin("socket.core", StaticLuaCallbacks.LoadSocketCore); AddBuildin("socket", StaticLuaCallbacks.LoadSocketCore); AddBuildin("mime.core", StaticLuaCallbacks.LoadMimeCore); AddBuildin("rapidjson", StaticLuaCallbacks.LoadRapidJson); AddBuildin("lpeg", StaticLuaCallbacks.LoadLpeg); AddBuildin("sproto.core", StaticLuaCallbacks.LoadSprotoCore); //AddBuildin("pack", StaticLuaCallbacks.LoadPack); LuaAPI.lua_newtable(L); //metatable of indexs and newindexs functions LuaAPI.xlua_pushasciistring(L, "__index"); LuaAPI.lua_pushstdcallcfunction(L, StaticLuaCallbacks.MetaFuncIndex); LuaAPI.lua_rawset(L, -3); LuaAPI.xlua_pushasciistring(L, Utils.LuaIndexsFieldName); LuaAPI.lua_newtable(L); LuaAPI.lua_pushvalue(L, -3); LuaAPI.lua_setmetatable(L, -2); LuaAPI.lua_rawset(L, LuaIndexes.LUA_REGISTRYINDEX); LuaAPI.xlua_pushasciistring(L, Utils.LuaNewIndexsFieldName); LuaAPI.lua_newtable(L); LuaAPI.lua_pushvalue(L, -3); LuaAPI.lua_setmetatable(L, -2); LuaAPI.lua_rawset(L, LuaIndexes.LUA_REGISTRYINDEX); LuaAPI.xlua_pushasciistring(L, Utils.LuaClassIndexsFieldName); LuaAPI.lua_newtable(L); LuaAPI.lua_pushvalue(L, -3); LuaAPI.lua_setmetatable(L, -2); LuaAPI.lua_rawset(L, LuaIndexes.LUA_REGISTRYINDEX); LuaAPI.xlua_pushasciistring(L, Utils.LuaClassNewIndexsFieldName); LuaAPI.lua_newtable(L); LuaAPI.lua_pushvalue(L, -3); LuaAPI.lua_setmetatable(L, -2); LuaAPI.lua_rawset(L, LuaIndexes.LUA_REGISTRYINDEX); LuaAPI.lua_pop(L, 1); // pop metatable of indexs and newindexs functions LuaAPI.xlua_pushasciistring(L, "xlua_main_thread"); LuaAPI.lua_pushthread(L); LuaAPI.lua_rawset(L, LuaIndexes.LUA_REGISTRYINDEX); translator.Alias(typeof(Type), "System.MonoType"); LuaAPI.lua_getglobal(L, "_G"); translator.Get(L, -1, out _G); LuaAPI.lua_pop(L, 1); errorFuncRef = LuaAPI.get_error_func_ref(L); if (initers != null) { for (int i = 0; i < initers.Count; i++) { initers[i](this, translator); } } translator.CreateArrayMetatable(L); translator.CreateDelegateMetatable(L); #if THREAD_SAFT || HOTFIX_ENABLE } #endif } private static List<Action<LuaEnv, ObjectTranslator>> initers = null; public static void AddIniter(Action<LuaEnv, ObjectTranslator> initer) { if (initers == null) { initers = new List<Action<LuaEnv, ObjectTranslator>>(); } initers.Add(initer); } public LuaTable Global { get { return _G; } } public T LoadString<T>(string chunk, string chunkName = "chunk", LuaTable env = null) { #if THREAD_SAFT || HOTFIX_ENABLE lock (luaEnvLock) { #endif if (typeof(T) != typeof(LuaFunction) && !typeof(T).IsSubclassOf(typeof(Delegate))) { throw new InvalidOperationException(typeof(T).Name + " is not a delegate type nor LuaFunction"); } int oldTop = LuaAPI.lua_gettop(L); if (LuaAPI.luaL_loadbuffer(L, chunk, chunkName) != 0) ThrowExceptionFromError(oldTop); if (env != null) { env.push(L); LuaAPI.lua_setfenv(L, -2); } T result = (T)translator.GetObject(L, -1, typeof(T)); LuaAPI.lua_settop(L, oldTop); return result; #if THREAD_SAFT || HOTFIX_ENABLE } #endif } public LuaFunction LoadString(string chunk, string chunkName = "chunk", LuaTable env = null) { return LoadString<LuaFunction>(chunk, chunkName, env); } public object[] DoString(string chunk, string chunkName = "chunk", LuaTable env = null) { #if THREAD_SAFT || HOTFIX_ENABLE lock (luaEnvLock) { #endif int oldTop = LuaAPI.lua_gettop(L); int errFunc = LuaAPI.load_error_func(L, errorFuncRef); if (LuaAPI.luaL_loadbuffer(L, chunk, chunkName) == 0) { if (env != null) { env.push(L); LuaAPI.lua_setfenv(L, -2); } if (LuaAPI.lua_pcall(L, 0, -1, errFunc) == 0) { LuaAPI.lua_remove(L, errFunc); return translator.popValues(L, oldTop); } else ThrowExceptionFromError(oldTop); } else ThrowExceptionFromError(oldTop); return null; #if THREAD_SAFT || HOTFIX_ENABLE } #endif } private void AddSearcher(LuaCSFunction searcher, int index) { #if THREAD_SAFT || HOTFIX_ENABLE lock (luaEnvLock) { #endif //insert the loader LuaAPI.xlua_getloaders(L); if (!LuaAPI.lua_istable(L, -1)) { throw new Exception("Can not set searcher!"); } uint len = LuaAPI.xlua_objlen(L, -1); index = index < 0 ? (int)(len + index + 2) : index; for (int e = (int)len + 1; e > index; e--) { LuaAPI.xlua_rawgeti(L, -1, e - 1); LuaAPI.xlua_rawseti(L, -2, e); } LuaAPI.lua_pushstdcallcfunction(L, searcher); LuaAPI.xlua_rawseti(L, -2, index); LuaAPI.lua_pop(L, 1); #if THREAD_SAFT || HOTFIX_ENABLE } #endif } public void Alias(Type type, string alias) { translator.Alias(type, alias); } int last_check_point = 0; int max_check_per_tick = 20; static bool ObjectValidCheck(object obj) { return (!(obj is UnityEngine.Object)) || ((obj as UnityEngine.Object) != null); } Func<object, bool> object_valid_checker = new Func<object, bool>(ObjectValidCheck); public void Tick() { #if THREAD_SAFT || HOTFIX_ENABLE lock (luaEnvLock) { #endif lock (refQueue) { while (refQueue.Count > 0) { GCAction gca = refQueue.Dequeue(); translator.ReleaseLuaBase(L, gca.Reference, gca.IsDelegate); } } last_check_point = translator.objects.Check(last_check_point, max_check_per_tick, object_valid_checker, translator.reverseMap); #if THREAD_SAFT || HOTFIX_ENABLE } #endif } //兼容API public void GC() { Tick(); } public LuaTable NewTable() { #if THREAD_SAFT || HOTFIX_ENABLE lock (luaEnvLock) { #endif int oldTop = LuaAPI.lua_gettop(L); LuaAPI.lua_newtable(L); LuaTable returnVal = (LuaTable)translator.GetObject(L, -1, typeof(LuaTable)); LuaAPI.lua_settop(L, oldTop); return returnVal; #if THREAD_SAFT || HOTFIX_ENABLE } #endif } private bool disposed = false; public void Dispose() { Dispose(true); System.GC.Collect(); System.GC.WaitForPendingFinalizers(); } public virtual void Dispose(bool dispose) { #if THREAD_SAFT || HOTFIX_ENABLE lock (luaEnvLock) { #endif if (disposed) return; Tick(); LuaAPI.lua_close(L); ObjectTranslatorPool.Instance.Remove(L); if (translator != null) { translator = null; } L = IntPtr.Zero; disposed = true; #if THREAD_SAFT || HOTFIX_ENABLE } #endif } public void ThrowExceptionFromError(int oldTop) { #if THREAD_SAFT || HOTFIX_ENABLE lock (luaEnvLock) { #endif object err = translator.GetObject(L, -1); LuaAPI.lua_settop(L, oldTop); // A pre-wrapped exception - just rethrow it (stack trace of InnerException will be preserved) Exception ex = err as Exception; if (ex != null) throw ex; // A non-wrapped Lua error (best interpreted as a string) - wrap it and throw it if (err == null) err = "Unknown Lua Error"; throw new LuaException(err.ToString()); #if THREAD_SAFT || HOTFIX_ENABLE } #endif } internal struct GCAction { public int Reference; public bool IsDelegate; } Queue<GCAction> refQueue = new Queue<GCAction>(); internal void equeueGCAction(GCAction action) { lock (refQueue) { refQueue.Enqueue(action); } } private string init_xlua = @" local metatable = {} local rawget = rawget local setmetatable = setmetatable local import_type = xlua.import_type local load_assembly = xlua.load_assembly function metatable:__index(key) local fqn = rawget(self,'.fqn') fqn = ((fqn and fqn .. '.') or '') .. key local obj = import_type(fqn) if obj == nil then -- It might be an assembly, so we load it too. obj = { ['.fqn'] = fqn } setmetatable(obj, metatable) elseif obj == true then return rawget(self, key) end -- Cache this lookup rawset(self, key, obj) return obj end -- A non-type has been called; e.g. foo = System.Foo() function metatable:__call(...) error('No such type: ' .. rawget(self,'.fqn'), 2) end CS = CS or {} setmetatable(CS, metatable) typeof = function(t) return t.UnderlyingSystemType end cast = xlua.cast if not setfenv or not getfenv then local function getfunction(level) local info = debug.getinfo(level + 1, 'f') return info and info.func end function setfenv(fn, env) if type(fn) == 'number' then fn = getfunction(fn + 1) end local i = 1 while true do local name = debug.getupvalue(fn, i) if name == '_ENV' then debug.upvaluejoin(fn, i, (function() return env end), 1) break elseif not name then break end i = i + 1 end return fn end function getfenv(fn) if type(fn) == 'number' then fn = getfunction(fn + 1) end local i = 1 while true do local name, val = debug.getupvalue(fn, i) if name == '_ENV' then return val elseif not name then break end i = i + 1 end end end xlua.hotfix = function(cs, field, func) local tbl = (type(field) == 'table') and field or {[field] = func} for k, v in pairs(tbl) do local cflag = '' if k == '.ctor' then cflag = '_c' k = 'ctor' end xlua.access(cs, cflag .. '__Hitfix0_'..k, v) -- at least one pcall(function() for i = 1, 99 do xlua.access(cs, '__Hitfix'..i..'_'..k, v) end end) end end "; public delegate byte[] CustomLoader(ref string filepath); internal List<CustomLoader> customLoaders = new List<CustomLoader>(); //loader : CustomLoader, filepath参数:(ref类型)输入是require的参数,如果需要支持调试,需要输出真实路径。 // 返回值:如果返回null,代表加载该源下无合适的文件,否则返回UTF8编码的byte[] public void AddLoader(CustomLoader loader) { customLoaders.Add(loader); } internal Dictionary<string, LuaCSFunction> buildin_initer = new Dictionary<string, LuaCSFunction>(); public void AddBuildin(string name, LuaCSFunction initer) { if (!initer.Method.IsStatic || !Attribute.IsDefined(initer.Method, typeof(MonoPInvokeCallbackAttribute))) { throw new Exception("initer must be static and has MonoPInvokeCallback Attribute!"); } buildin_initer.Add(name, initer); } //The garbage-collector pause controls how long the collector waits before starting a new cycle. //Larger values make the collector less aggressive. Values smaller than 100 mean the collector //will not wait to start a new cycle. A value of 200 means that the collector waits for the total //memory in use to double before starting a new cycle. public int GcPause { get { #if THREAD_SAFT || HOTFIX_ENABLE lock (luaEnvLock) { #endif int val = LuaAPI.lua_gc(L, LuaGCOptions.LUA_GCSETPAUSE, 200); LuaAPI.lua_gc(L, LuaGCOptions.LUA_GCSETPAUSE, val); return val; #if THREAD_SAFT || HOTFIX_ENABLE } #endif } set { #if THREAD_SAFT || HOTFIX_ENABLE lock (luaEnvLock) { #endif LuaAPI.lua_gc(L, LuaGCOptions.LUA_GCSETPAUSE, value); #if THREAD_SAFT || HOTFIX_ENABLE } #endif } } //The step multiplier controls the relative speed of the collector relative to memory allocation. //Larger values make the collector more aggressive but also increase the size of each incremental //step. Values smaller than 100 make the collector too slow and can result in the collector never //finishing a cycle. The default, 200, means that the collector runs at "twice" the speed of memory //allocation. public int GcStepmul { get { #if THREAD_SAFT || HOTFIX_ENABLE lock (luaEnvLock) { #endif int val = LuaAPI.lua_gc(L, LuaGCOptions.LUA_GCSETSTEPMUL, 200); LuaAPI.lua_gc(L, LuaGCOptions.LUA_GCSETSTEPMUL, val); return val; #if THREAD_SAFT || HOTFIX_ENABLE } #endif } set { #if THREAD_SAFT || HOTFIX_ENABLE lock (luaEnvLock) { #endif LuaAPI.lua_gc(L, LuaGCOptions.LUA_GCSETSTEPMUL, value); #if THREAD_SAFT || HOTFIX_ENABLE } #endif } } public void FullGc() { #if THREAD_SAFT || HOTFIX_ENABLE lock (luaEnvLock) { #endif LuaAPI.lua_gc(L, LuaGCOptions.LUA_GCCOLLECT, 0); #if THREAD_SAFT || HOTFIX_ENABLE } #endif } public void StopGc() { #if THREAD_SAFT || HOTFIX_ENABLE lock (luaEnvLock) { #endif LuaAPI.lua_gc(L, LuaGCOptions.LUA_GCSTOP, 0); #if THREAD_SAFT || HOTFIX_ENABLE } #endif } public void RestartGc() { #if THREAD_SAFT || HOTFIX_ENABLE lock (luaEnvLock) { #endif LuaAPI.lua_gc(L, LuaGCOptions.LUA_GCRESTART, 0); #if THREAD_SAFT || HOTFIX_ENABLE } #endif } public bool GcStep(int data) { #if THREAD_SAFT || HOTFIX_ENABLE lock (luaEnvLock) { #endif return LuaAPI.lua_gc(L, LuaGCOptions.LUA_GCSTEP, data) != 0; #if THREAD_SAFT || HOTFIX_ENABLE } #endif } public int Memroy { get { #if THREAD_SAFT || HOTFIX_ENABLE lock (luaEnvLock) { #endif return LuaAPI.lua_gc(L, LuaGCOptions.LUA_GCCOUNT, 0); #if THREAD_SAFT || HOTFIX_ENABLE } #endif } } } } LuaException: c# exception:System.Collections.Generic.KeyNotFoundException: The given key was not present in the dictionary. at System.Collections.Generic.Dictionary`2[System.String,FishPathData].get_Item (System.String key) [0x000a2] in /Users/builduser/buildslave/mono/build/mcs/class/corlib/System.Collections.Generic/Dictionary.cs:150 at FishPathManager.getPath (System.String name) [0x00021] in D:\Lua_Dating546\Assets\Scripts\Util\FishPathManager.cs:117 at fish.setPath (System.String pathName, Single lifeTime, Boolean freeGroup, Single roat, Single speed) [0x00000] in D:\Lua_Dating546\Assets\Scripts\Util\fish.cs:744 at CSObjectWrap.fishWrap.setPath (IntPtr L) [0x000a4] in D:\Lua_Dating546\Assets\XLua\Gen\fishWrap.cs:403 stack traceback: [C]: in method 'setPath' game.fish.gameobject.Fish:192: in function 'game.fish.gameobject.Fish.setPath' game.fish.gameobject.Fish:131: in function 'game.fish.gameobject.Fish.initInfo' game.fish.view.FishGameRoot:881: in function 'game.fish.view.FishGameRoot.createOneFish' game.fish.view.FishGameRoot:776: in function 'game.fish.view.FishGameRoot.Update' base.system.UpdateBeat:22: in function 'base.system.UpdateBeat.Update' base.Main:13: in function 'update' XLua.LuaEnv.ThrowExceptionFromError (Int32 oldTop) (at Assets/XLua/Src/LuaEnv.cs:367) XLua.DelegateBridge.SystemVoid () (at Assets/XLua/Gen/DelegatesGensBridge.cs:34) LuaFramework.LuaManager.Update () (at Assets/Scripts/Manager/LuaManager.cs:111)
最新发布
07-25
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值