do I need pairs or ipairs for this?

Posted by Kevnuke on Sun 31 Mar 2019 12:11 AM — 7 posts, 23,820 views.

USA #0
I'm taking JSON data from IRE GMCP messages and am trying to get the named index from the table. I keep getting the value and not the key AND value. I tried to test it in immediate execution but MUSHclient yelled at me for trying to
require "ipairs"


I want to have whatever the index names are in the JSON data be what the index is named in the Lua table.
For example, if I get this from the Achaea:

Char.Name { "name": "myname", "fullname": "myfullname" }


What I'll end up with is:

stats = {
    name      = "myname",
    fullname  = "myfullname"
}

I've tried this and a few variations of it so far just to see if I can get the name of the index to print:

string = [[{"name": "myname", "fullname": "myfullname"}]] -- many values for fullname have single quotes in them.
test = json.decode('[' .. string .. ']')[1]
for k,v in pairs (test) do
print (test[k])
end
Amended on Sun 31 Mar 2019 12:13 AM by Kevnuke
USA #1
Omg I'm dumb, I was doing too much. This worked:

function test_data()
	string = [[{"name": "myname","fullname": "myfullname"}]]
	test = json.decode('[' .. string .. ']')[1]
	for k,v in pairs (test) do
		print (k .. " " .. v)
	end
end
Australia Forum Administrator #2
It looks like you've solved it, but for reference ipairs only returns numerically keyed items starting at 1 (and stopping if it hits a gap).

So, for alpha-keyed items pairs is more appropriate.
USA #3
ohhh so that wouldn't have worked anyway. Thanks I always forget the difference. :D

But why did it throw a bunch of errors when i tried to require ipairs? looked like one for each dll. My MUSHclient folder is in my OneDrive folder, if that makes a difference
Amended on Sun 31 Mar 2019 06:51 AM by Kevnuke
Australia Forum Administrator #4
You don't need to require ipairs. It is a built-in function.

It would be like doing this:


require "print"


You don't need to do that, and there would be no file print.lua in your directory.
Amended on Sun 31 Mar 2019 08:26 AM by Nick Gammon
USA #5
Hmm I see. I just thought it was weird when I tried ipairs and it did nothing. No output, no errors, nothing. I'm not really used to that. lol
Australia Forum Administrator #6
It did nothing because there were no numeric keys.