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 Answers
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"
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) )
next. Without it, orpairs(which usesnext), there is not other way. - lhft[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 sequencek1,k2,…you can getv1,v2,…byt[k1], t[k2], …and because you can do look-ups both ways, you can getkback fromt[v]. - nobody