Why does pairs exist? - lua

I'm sure many of you already know that the pairs function just returns next, t, and nil. What is the point of this? I've heard some say it's for readability but I think it just confuses people about the structure of a for loop.
So why does it exist?

In Lua 5.2, the __pairs and __ipairs metamethods were added to allow tables to have custom iterators. Not only that, but it's easier to read. There's also a __next metamethod as of Lua 5.2.
Reference

Related

Is there a way to introspect a function in Lua?

I am creating a game in love2d (LuaJIT) and I am creating a debug window for changing values at runtime. I was able to do that, however, I also now want to be able to call functions. For example, I traverse a table and there is a function in this table called "hello" which is written like this:
self.hello = function(str, num)
print(string.format("%s: %d", str, num))
end
From the expression of type(object.hello) I only see function. If it had been a table, I could have traversed it and see the keys and values, but it is just a "function" and I have no idea how to properly call it, as I don't know what arguments does it take and how many. Is there a way to find this out at runtime in lua? Maybe this information is also stored in some table elsewhere?
it is just a "function" and I have no idea how to properly call it
Neither does Lua. As far as Lua is concerned, any Lua function can take any number of parameters and return any number of parameters. These parameters could be of any type, as could its return values.
Lua itself does not store this information. Or at least, not in any way you could retrieve without doing some decompiling of its byte-code. And since you're using LuaJIT, that "decompiling" might require decompiling assembly.

What does a period signify in lua?

I have some proprietary implementation of lua, and all the variables exposed to me are in the form of 'ME.AV123' (for example). What is 'ME'? Is it a namespace? Is it a class? Is there a way to tell? Should I be able to do some sort of type(ME) (which does not seem to work)? In the documentation it says the keyword 'ME' is used to access the objects in the local database.
Follow-up, bonus question - Is there a way to get to all the variables in ME? I.e. - like the global variables use _G[varname], is there an equivalent way to do this for ME?
I apologize if I am not giving you enough. I am new to Lua, and I have relatively limited functionality through this .... thing.
Just to maybe put a finer point on it, and illustrate what I am actually trying to do:
I can interact with some set of variables, which are all in the documentation. All of them are name(addressed?) 'ME.varname'. So, to set 'AV120' to '1', I would say ME.AV120 = 1. I need to set some.. few dozen of these things, and would like a way to loop through all the variables, setting them as I go. I would think something like:
for i,j in pairs(mySettingsTable) do
ME[i] = j
end
Does this make sense?
From the Lua reference manual:
https://www.lua.org/manual/5.3/manual.html#2.1
The language supports this representation by providing a.name as
syntactic sugar for a["name"].
So ME.AV123 is the same as ME["AV123"].
It is just a more convenient form of indexing.
type() returns a string, in case you're wondering why the function does nothing on it's own. print(type(ME)) should work.

modify # operator in lua

I have made a lua console on the love2d engine which is irrelevant. I am trying to upgrade the metatables to be able to effect more things (the pairs function, change the metatable on another table instead of the targeted one etc.) and one of the addons I am making is a __changeindex event for when you modify an existing index.
In order to do this I have to give the user a dummy table that holds no values and when they try to add something check if that is already defined in the real table, if it is then call __changeindex, if it is not then call __newindex. This works perfectly however this causes many other Lua table functions to stop working (for loops/getmetatable/setmetatable). I have made workarounds for most of those issues and they work fine but I cannot get the #t operator working, I would like to be able to say
t1={1,2,3}
t2=setmetatable({},{__getn=function(self) return #t1 end})
and then #t2 should really return #t1. Is there any way for me to do this?
my existing code for this can be found here
EDIT: this is my first post so I apologise if I have not followed the posting rules perfectly, I tried :) also if anyone has a way to make the fake and real tables garbage collect I would really appreciate it
There no __getn metamethod. Try __len instead. This works only on Lua 5.2
You cannot overload the # operator for tables in Lua 5.1
You could use userdata to create a proxy object:
t = newproxy(true)
getmetatable(t).__len = function()
return 5
end
print(#t) --> 5
Note however, that the newproxy function is undocumented.

Human readable string representation of table in Lua

I am new to Lua and want to print the contents of a table for debugging purposes. I can do that by iterating over the table myself. However, since this strikes me as a very common problem, I expect there must be an out of the box way of doing that or someone must have written a nice library that does that. WHat's the standard way of doing this in Lua?
For better or worse, there's no standard. Lua is known for what it excludes as much as for what it includes. It doesn't make assumptions about proper string representations because there's no one true way to handle things like formats, nested tables, function representation, or table cycles. That being said, it doesn't hurt to start with a "batteries-included" Lua library. Maybe consider Penlight. Its pl.pretty.write does the trick.
This is an instance of the general problem of table serialization.
Take a look at the Table Serialization page at lua-users for some serious implementations.
My throw at it is usually quickly defining a function like
function lt(t) for k,v in pairs(t) do print(k,v) end end
See table.print in https://github.com/rimar/lua-reactor-light/blob/master/util.lua it was probably borrowed from lualogging library

Are there any downsides to passing in an Erlang record as a function argument?

Are there any downsides to passing in an Erlang record as a function argument?
There is no downside, unless the caller function and the called function were compiled with different 'versions' of the record.
Some functions from erlangs standard library do indeed use records in their interfaces (I can't recall which ones, right now--but there are a few), but in my humble opinion, the major turnoff is, that the user will have to include your header file, just to use your function.
That seems un-erlangy to me (you don't ever do that normally, unless you're using said functions from the stdlib), creates weird inter-dependencies, and is harder to use from the shell (I wouldn't know from the top of my head how to load & use records from the shell -- I usually just "cheat" by constructing the tuple manually...)
Also, handling records is a bit different from the stuff you usually do, since their keys per default take the atom 'undefined' as value, au contraire to how you usually do it with proplists, for instance (a value that wasn't set just isn't there) -- this might cause some confusion for people who do not normally work a lot with records.
So, all-in-all, I'd usually prefer a proplist or something similar, unless I have a very good reason to use a record. I do usually use records, though, for internal state of for example a gen_server or a gen_fsm; It's somewhat easier to update that way.
I think the biggest downside is that it's not idiomatic. Have you ever seen an API that required you to construct a record and pass it in?
Why would you want to do something that's going to feel foreign to any erlang programmer? There's a convention already in use for optional named arguments to functions. Inventing yet another way without good cause is pointless.

Resources