gpt4 book ai didi

pointers - Lua表->地址和地址->表

转载 作者:行者123 更新时间:2023-12-04 02:50:57 27 4
gpt4 key购买 nike

想象一下下面的代码:

Mytable={}
print(Mytable)

打印类似 Table: 12345 的内容。如何在不弄乱 tostring 的返回值的情况下从 Lua 获取“地址”部分,更重要的是,如何取回表?

在代码中:

addr=table2address(Mytable)
-- type(addr) is number, addr is 12345
Othertable=address2table(addr)
-- type(Othertable) is table, Othertable==Mytable is true (same reference)

有没有办法在Lua中实现这两个功能?如果不是,我该如何在 C 中执行此操作?

编辑:table2address 可以通过从 tostring(Mytable) 中删除 Table: 来完成,但前提是元方法 __tostring 没有定义,所以我想避免这种情况。

最佳答案

简单的实现满足您的所有标准,但有一个:

function table2address(Mytable) return Mytable end
function address2table(addr) return addr end

演示:

> Mytable={}
> print(Mytable)
table: 0x7fe511c0a190
> addr = table2address(Mytable)
> Othertable=address2table(addr)
> =type(Othertable)
table
> print(Othertable==Mytable)
true

稍微复杂一点的实现可以满足您的所有条件:

t2at = {}

function table2address(Mytable)
local addr = t2at[Mytable]
if addr == nil then
addr = #t2at + 1
t2at[Mytable] = addr
t2at[addr] = Mytable
end
return addr
end

function address2table(addr)
return t2at[addr]
end

演示:

> Mytable={}
> addr = table2address(Mytable)
> Othertable=address2table(addr)
> =type(Othertable)
table
> print(Othertable==Mytable)
true
> =type(addr)
number

那么,为什么地址对您很重要?

在像 Lua 这样的垃圾收集语言中,只能保存对对象的引用,而不是地址。 [当前的实现可能会或可能不会在 GC 期间移动对象,但除了 userdata 和 Lua 状态之外,Lua 有权移动任何东西。]

附录

回复:“地址永远不会随机化(在 2 个新的交互式 lua 实例中尝试 print({}))”

e$ lua
Lua 5.2.2 Copyright (C) 1994-2013 Lua.org, PUC-Rio
> print({})
table: 0x7fdaca4098c0
> ^D
e$ lua
Lua 5.2.2 Copyright (C) 1994-2013 Lua.org, PUC-Rio
> print({})
table: 0x7fb02a4098c0
> ^D
e$

回复:确实需要物理地址

查看实现打印内容的函数 luaL_tolstring;它有(在 Lua 5.2.2 中):

  default:
lua_pushfstring(L, "%s: %p", luaL_typename(L, idx),
lua_topointer(L, idx));
break;

因此,lua_topointer(L, idx) 是获取表地址所需的函数。

关于pointers - Lua表->地址和地址->表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17763223/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com