2

I am very new to Lua and am in need of assistance. I am trying to create a list of objects that have a name and a message. I need to be able to send JSON to my app like:

{{"name":"Joe","Message":"This is a test"),{....}}

From what I've read this could be accomplished with tables, but it does not seem to be working, what I have tried so far is

message = {}
messages = {}

message["name"] = "Joe"
message["message"] = "This is a Message"

messages["1"] = ??  <--- I don't know what to do here
4
  • Lua is a proper name, not an acronym. No need for the ALL CAPS. Commented Oct 4, 2012 at 2:59
  • Admittedly, my JSON is a bit rusty, but that seems to be invalid JSON. Could you correct it? Commented Oct 4, 2012 at 3:01
  • That is very invalid JSON and probably the source of your confusion :) Commented Oct 4, 2012 at 5:28
  • I'm sorry i miss typed the json Commented Oct 4, 2012 at 16:50

1 Answer 1

8

Assuming you fix your JSON code, which should probably look something like {{"name":"Joe","Message":"This is a test"},{....}}, you can use the following code:

message = {name = "Joe", Message = "This is a Message"} -- capitalization in "Message" may matter
messages = {}
messages[1] = message

This is the same as:

message = {}
message["name"] = "Joe" -- or message.name = "Joe"
message["Message"] = "This is a Message" -- or message.Message = "...."
messages = {}
messages[1] = message -- the value of that element is a table

Note that I used [1] and not ["1"], which are two different keys. Given your structure, you do want to use [1].

Sign up to request clarification or add additional context in comments.

2 Comments

Also, this is Lua, you can write message.name and message.Message instead of message["name"] and message["Message"]. And you should probably write local message = {} and local messages = {}.
@catwell: right, I mentioned .name and .Message as a comment in the example.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.