Lua表格->地址和地址->表格

假设有以下代码:

Mytable={}
print(Mytable)

输出类似于 Table: 12345。我该如何在 Lua 中获取“地址”部分,而不会影响 tostring 的返回值,更重要的是,我该如何将该表格返回?

在代码中:

addr=table2address(Mytable)
-- type(addr) 是 number,addr 是 12345
Othertable=address2table(addr)
-- type(Othertable) 是 table,Othertable==Mytable 为 true(相同引用)

是否有任何方法在 Lua 中实现这两个函数?如果不是,那么我该如何通过 C 实现(如何实现)?

编辑:table2address 可以通过从 tostring(Mytable) 中去掉 Table: 来完成,但只有在未定义元方法 __tostring 的情况下才能这样做,因此我希望避免这种情况。

点赞
用户33252
用户33252

Lua中对象地址的作用

一个简单的实现符合你的所有标准,除了一个:

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期间移动对象,但除了较低层次的数据类型和Lua状态之外,Lua具有移动任何东西的许可。]

补充说明

关于“地址从不被随机化(在两个新的交互式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,它实现了print的核心;它在Lua 5.2.2中有:

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

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

2013-07-20 14:56:01