Question

By using Python we can redefine string into dictionary.

Example :

var = "testing"
var = {'body': var}
print var['body']
'testing'

With Lua I want to do same . I want to convert string object into table .

My try :

> var = "testing"
> var = {'body', var}
> print(var)
table: 0x12b2930
> for i,j in pairs(var) do
>> print(i)
>> print(j)
>> end
1
body
2
testing
> 

With above example I can fetch testing string with

> print(var[2])
testing
>

Above code is not fulfilling my requirements. I want to store the value 'testing' with "body" key .
I want to fetch like below :

print(var['body'])
'testing'

Please help me on this

Was it helpful?

Solution

var = "testing"
var = {body = var}
print(var.body)
print(var["body"])

Comma in table construction separates table entries. So by specifying {"body", "testing"}, you create two entries with keys 1, 2 that are equal to "body" and "testing", respectively, since that is how you initialise a sequential array.

If you want to assign arbitrary keys to each value, you have to use =, as in {key1 = "body", key2 = "testing"}. Now you can access those elements in two ways. One is object like, using dot:

tab1.key1

And one is array/map like, using square brackets:

tab1["key1"].

In the second example, you have to pay attention to quotes. If you use double quotes, you're accessing a key directly. If not (tab1[key1]), you're using value stored in a variable named key1 as key specifier.

OTHER TIPS

The Lua code closest to the Python code is

var = "testing"
var = {['body'] = var}
print(var['body'])
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top