neolithos / neolua

A Lua implementation for the Dynamic Language Runtime (DLR).
https://neolua.codeplex.com/
Apache License 2.0
466 stars 76 forks source link

Issues using table.insert ? #131

Closed jesusgumbau closed 2 years ago

jesusgumbau commented 3 years ago

NeoLua Version: 1.3.13

Hi, I am having issues trying to write a Lua function that copies the list apssed as parameter.

This doesn't seem to work:

function copy(list)
    -- Copy the input list
    local copy = {}
    foreach item in list do
        table.insert(copy, item)
    end
    return copy
end

But This works as expected:

function copy(list)
    -- Copy the input list
    local copy = {}
    copy = list
    return copy
end

I tried require("table") but still not working. Any ideas?

neolithos commented 3 years ago

Both code blocks will not do what you want: http://lua-users.org/wiki/CopyTable

jesusgumbau commented 3 years ago

True, but I didn't want to do a deep copy. Just have 2 tables containing the same elements.

Shoudn't in both cases the function return a table populated with elements? I don't seem to get it with the first block of code.

PS: Actually what i wanted is a function that returns a subset of the input list. I just reduced the code to illustrate the "issue".

neolithos commented 3 years ago

May be this is what you looking for:

for k,v in pairs(t) do
   c[k] = v;
end;

This short snippet copies all members. You can filter the key k.

Less memory consuming would be to use metatables.

For an easy deep copy, there is also:

table.merge