Lua find a key from a value

If you find yourself needing to get the key from the value of a table, consider inverting the table as in function table_invert(t) local s={} for k,v in pairs(t) do s[v]=k end return s end

How to dump a table to console?

If the requirement is “quick and dirty” I’ve found this one useful. Because if the recursion it can print nested tables too. It doesn’t give the prettiest formatting in the output but for such a simple function it’s hard to beat for debugging. function dump(o) if type(o) == ‘table’ then local s=”{ ” for k,v … Read more

ESP8266 NodeMCU Running Out of Heap Memory

There was a problem in the NodeMCU docs with the socket:send example you seem to have based your implementation on. We discussed it and I fixed it. An improved version of your code is this: gpio.mode(3, gpio.OUTPUT) srv = net.createServer(net.TCP, 28800) print(“Server created… \n”) local pinState = 0 srv:listen(80, function(conn) conn:on(“receive”, function(sck, request) local _, … Read more

Safely remove items from an array table while iterating

the general case of iterating over an array and removing random items from the middle while continuing to iterate If you’re iterating front-to-back, when you remove element N, the next element in your iteration (N+1) gets shifted down into that position. If you increment your iteration variable (as ipairs does), you’ll skip that element. There … Read more

How to get number of entries in a Lua table?

You already have the solution in the question — the only way is to iterate the whole table with pairs(..). function tablelength(T) local count = 0 for _ in pairs(T) do count = count + 1 end return count end Also, notice that the “#” operator’s definition is a bit more complicated than that. Let … Read more