4 ms·
Learning it recently for a small game design, I was surprised that you couldnt easily copy a table, and even more suprised you needed "metatables" to do it...th
by petee 4y ago
Learning it recently for a small game design, I was surprised that you couldnt easily copy a table, and even more suprised you needed "metatables" to do it...the extra steps seem far from simple.
Maybe I'm just missing something. If I recall, I was simply trying to create a new 'object' (game character) from a template but it required metatable boiler plate that just made no sense to me.
Many languages, this is simply a = b, or at most allocating some space first.
- boffinAudio 4y agoYou might find it handy to add lua-enumerable.lua to your standard set of Lua-project modules: https://github.com/mikelovesrobots/lua-enumerable/blob/master/lua-enumerable.lua https://github.com/mikelovesrobots/lua-enumerable/blob/maste... See: table.dup()
- nmz 4y agoNOTE: Doesn't copy metamethods, doesn't copy subtables either.
- DayDollar 4y agoIn many scripting languages this is not the case, and you are ever only passing around references. Python comes to mind. Lots of people obviously have a problem with this as it deeply different from the algebra derived assignment syntax. local a = b creates a local copy, but even then, its not a deepcopy, containing references to other tables.
- kzrdude 4y agopython has both .copy() methods and a copy module. That's not to highlight Python's strengths, but an indication that it's a complex topic in Python - it has footguns here. The copy module might even do the wrong thing for a given object.
- naniwaduni 4y agoThe algebra-derived assignment syntax kind of falls apart with mutation anyway.
- scythe 4y ago>I was surprised that you couldn't easily copy a table Lua's designers have a sort of maxim "if it can't be done perfectly, let the user roll their own". This can be frustrating, but for table-copying it's not surprising. Do you copy subtables by reference or value? What about recursive tables? Mutually recursive subtables? Closures in tables? And then userdata can contain references that are opaque to the language runtime. It's not easy to define the behavior of deep copy in the fully general case.