1
votes

Hello im a newbie in Lua i just want to know if there is a way to get key and value of table not using pairs,ipairs,next or other iterators? thanks in advance.!

2
actually its my assignment creating a morse code..using pairs it can be done easily. but our teacher said if we try not using pairs or iterators he will give us better grades. i was already stuck whole day searching a way to not use iterators but i still haven't found a way... - Guadrian Yaba
The primitive function for traversing tables is next. Without it, or pairs (which uses next), there is not other way. - lhf
yeah that is why im soo confused on how to traverse table without using the function built by lua... thank for the reply - Guadrian Yaba
If you build the table and no key is equal to a value, you can say t[k], t[v] = v, k (i.e. add bidirectional entries). Then, if you can enumerate one of them externally (e.g. letters a,b,c…), you can also enumerate the other (here: morse code) because if you have the key sequence k1,k2,… you can get v1,v2,… by t[k1], t[k2], … and because you can do look-ups both ways, you can get k back from t[v]. - nobody
Am I losing my mind? I commented twice on this post yesterday "this makes no sense" and "is it an array? Or a dictionary?" But now they're gone... - warspyking

2 Answers

2
votes

I don't believe this is possible, as you've phrased your question in such a way that implies that the key is unknown. The only way to check for a certain value and its corresponding key would be to iterate through the whole table.

However, maybe I misunderstood and you want to get a certain value from a key without iterating through the whole table.

Say you have a table named morse as follows:

morse = { a = ".-"; b = "-..."; } -- And so on

If you wanted to convert a single character to morse you could do as follows:

morse["a"] --Which will return the string ".-"

You can do the opposite, and define a table with all the morse values and their corresponding letters like below. Note the use of square brackets to 'escape' the characters.

morse = { [".-"] = "a"; ["-..."] = "b" }
morse[".-"] -- This will return "a"
0
votes

Based on your comment, I think you are looking for a string substitution using a mapping table. I think you can use string.gsub here (if your teacher still insists that .gsub is an iterator; you can ask them politely that you are unaware of the method they claim and would be delighted to actually learn about the same):

local str = "sos sos sos"
local morse = {s = "...", o = "---"}

print( str:gsub("%a", morse) )