FinnTheHuman
FinnTheHuman

Reputation: 1155

Is there a way to iterate over a userdata, like pairs and ipairs do with a table?

Is there a function to iterate over the entries in a userdata value? I'm trying to list every field and its value in some userdata variable, just like pairs would do:

local function list_entries ( obj )
    for k, v in pairs ( obj ) do
        print ( k .. ": " .. tostring ( v ) )
    end
end

pairs doesn't work for userdata, so is there a solution to this?

Upvotes: 2

Views: 4313

Answers (1)

Nicol Bolas
Nicol Bolas

Reputation: 474266

Lua 5.2+ provides the __pairs and __ipairs metamethods. If a userdata provides them, then the corresponding Lua iterator will call them to get the iteration data. This means that the userdata must explicitly choose to provide iteration support; it cannot be forced on it.

After all, userdata doesn't actually contain anything (at least, as far as Lua is concerned). All of its Lua functionality comes through the metamethods it provides. data.val only works because the userdata has an __index metamethod that can take the string "val". Iteration is no different; if the userdata doesn't provide it, you can't do it.

In earlier versions of Lua, you can replace the existing pairs and ipairs functions with something that does what the 5.2+ versions do: look for the metamethods and use them if they're available. Of course, this can only be done from C, since only C code can get the metatable for userdata.

Upvotes: 5

Related Questions