lua 中指向等效指针的指针是什么

what is the pointer to pointer equivalent in lua

我知道您可以像 lua 中的指针一样使用表。话虽这么说,指向指针的指针会是什么样子?它们看起来像 dp = {p = {}} 吗?如果是这样,下面的 C 代码在 lua 中的等效项是什么?

void InsertItem(node **head, node *newp){
    node **dp = head;

    while((*dp) && (*dp)->value > newp->value
    {
        dp = &(*dp)->next;
    }

    newp->next = *dp;
    *dp = newp;
}

是的,双指针可能被翻译成 Lua 作为嵌套 table。

local function InsertItem(head, newitem)
   while head.next and head.next.value > newitem.value do
      head = head.next
   end
   newitem.next = head.next
   head.next = newitem
end

-- Typical Usage:
local head = {}
InsertItem(head, {value = 3.14})
InsertItem(head, {value = 42})
InsertItem(head, {value = 1})

-- Now the data is the following:
-- head  = {next = elem1}
-- elem1 = {next = elem2, value = 42  }
-- elem2 = {next = elem3, value = 3.14}
-- elem3 = {              value = 1   }

C 指针和 Lua 表之间的最大区别在于,在 C 中,您可以获取变量的地址并将其传递给函数以对其进行修改。您不能在 Lua 中执行此操作,但该函数始终可以 return 修改后的值。

Would they look something like dp = {p = {}}?

是的,这与您可以到达 Lua 中的指针的指针一样接近。

if so what would the equivalent to the c code below be in lua?

链表在递归的情况下往往工作得更顺畅:

local function InsertItem(head, newp)
  if not head or head.value <= newp.value then
    newp.next = head
    return newp
  end
  head.next = InsertItem(head.next, newp)
  return head
end