how do i iterate the tables parameters which is present under the main table? - lua

In lua ,im calling a function which returns a table variable that contains many parameter internally..but when i get that value i couldnt access the paramter which is present in the table. I can see the tables parameter in the original function in the form of
[[table:0x0989]]
{
[[table:0x23456]]
str = "hello"
width = 180
},
[[table:0x23489]]
{
str1 = "world"
}
it shows like this.but when it returns once i can able to get the top address of table like [[table:0x0989]]..when i tried acessing the tables which is present inside the main table.it is showing a nil value...how do i call that ?? can anyone help me??

If I'm reading it correctly you're doing this:
function my_function ()
--do something
return ({a=1, b=2, c=3})
end
From that you should be able to do this:
my_table = my_function()
then
print(my_table.a) --=> 1
print(my_table.b) --=> 2
print(my_table.c) --=> 3

Related

Lua: Passing index of nested tables as function arguments?

Is it possible to have a function that can access arbitrarily nested entries of a table?
The following example is just for one table. But in my real application I need the function to check several different tables for the given (nested) index.
local table1 = {
value1 = "test1",
subtable1 = {
subvalue1 = "subvalue1",
},
}
local function myAccess(index)
return table1[index]
end
-- This is fine:
print (myAccess("value1"))
-- But how do I access subtable1.subvalue1?
print (myAccess("subtable1.subvalue1???"))
You won't be able to do this using a string unless you use load to treat it as Lua code or make a function to walk on a table.
You can make a function which will split your string by . to get each key and then go one by one.
You can do this using gmatch + one local above gmatch with current table.
#Spar: Is this what you were suggesting? It works anyway, so thanks!
local table1 = {
value1 = "test1",
subtable1 = {
subvalue1 = "subvalue1",
},
}
local function myAccess(index)
local returnValue = table1
for key in string.gmatch(index, "[^.]+") do
if returnValue[key] then
returnValue = returnValue[key]
else
return nil
end
end
return returnValue
end
-- This is fine:
print (myAccess("value1"))
-- So is this:
print (myAccess("subtable1.subvalue1"))

lua: user input to reference table

I am having trouble with my tables, I am making a text adventure in lua
local locxy = {}
locxy[1] = {}
locxy[1][1] = {}
locxy[1][1]["locdesc"] = "dungeon cell"
locxy[1][1]["items"] = {"nothing"}
locxy[1][1]["monsters"] = {monster1}
The [1][1] refers to x,y coordinates and using a move command I can successfully move into different rooms and receive the description of said room.
Items and monsters are nested tables since multiple items can be held there (each with their own properties).
The problem I am having is getting the items/monsters part to work. I have a separate table such as:
local monsters = {}
monsters["rat"] = {}
monsters["rat"]["Name"] = "a rat"
monsters["rat"]["Health"] = 5
monsters["rat"]["Attack"] = 1
I am using a table like this to create outlines for various enemy types. The monster1 is a variable I can insert into the location table to call upon one of these outlines, however I don't know how to reference it.
print("You are in ", locxy[x][y]["locdesc"]) -- this works
print("You can see a ", locxy[x][y]["monsters]["Name"],".") - does not work
So I would like to know how I can get that to work, I may need a different approach which is fine since I am learning. But I would also specifically like to know how to / if it possible to use a variable within a table entry that points to data in a separate table.
Thanks for any help that can be offered!
This line
locxy[x][y]["monsters]["Name"]
says
look in the locxy table for the x field
then look in the y field of that value
look in the "monsters"` field of that value
then look in the "Name" field of that value
The problem is that the table you get back from locxy[x][y]["monsters"] doesn't have a "Name" field. It has some number of entries in numerical indices.
locxy[x][y]["monsters][1]["Name"] will get you the name of the first monster in that table but you will need to loop over the monsters table to get all of them.
Style notes:
Instead of:
tab = {}
tab[1] = {}
tab[1][1] = {}
you can just use:
tab = {
[1] = {
{}
}
}
and instead of:
monsters = {}
monsters["rat"] = {}
monsters["rat"]["Name"] = "foo"
you can just use:
monsters = {
rat = {
Name = "foo"
}
}
Or ["rat"] and ["Name"] if you want to be explicit in your keys.
Similarly instead of monsters["rat"]["Name"] you can use monsters.rat.Name.

Lua pass function argument as a table key

I'm working on exporting the contents of a Lua table to a HTML File so I can display the contents in the browser. Right now I'm having problems with passing a function argument as a table key.
I have a sparse table as such:
map = {}
for x = 1, 20 do
map[x] = {}
for y = 1, 20 do
map[x][y] = {}
map[x][y].node = math.random(1,20)
map[x][y].image = "path/to/image.png"
end
end
I pass the table to my function as such:
htmParser:_dumpSparseToHTML(map, 20, 20) where map = table I want to pass, 20,20 = width and height of the array. Somewhere in _dumpSparseToHTML I write the values of v.node and v.image to the file. How do I handle the exact same thing without knowing the name of the keys in the table? For example map could contain map[x][y].value, map[x][y].gfx, map[x][y].nodeType, and I would like to pass them as htmParser:_dumpSparseToHTML(map, 20, 20, value, gfx, nodeType, etc).
I know that Lua can handle a variable number of arguments, by defining the function as: _dumpSparseToHTML(map, 20, 20, ...). I tried to do the following:
--_table = map
for i,v in ipairs(arg) do
file:write("<td>".._table[x][y].v.."</td>)
end
The error I get is: "attempt to concatenate field 'v' (a nil value).
So, my question is: how do I pass a variable number of arguments as table keys?
You need to use _table[x][y][v] for that. _table[x][y].v is _table[x][y]["v"].

Displaying Lua tables to console by concatenating to string

I was wondering whether it is possible to display tables in the console. Something like:
player[1] = {}
player[1].Name = { "Comp_uter15776", "maciozo" }
InputConsole("msg Player names are: " .. player[1].Name)
However, this is obviously wrong as I receive the error about it not being able to concatenate a table value. Is there a workaround for this?
Much thanks in advance!
To turn an array-like table into a string, use table.concat:
InputConsole("msg Player names are: " .. table.concat(player[1].Name, " "))
The second argument is the string placed between each element; it defaults to "".
to make life easier on yourself for this... i'd recommend naming elements in the inner tables as well. this makes the code above easier to read when you need to get at specific values in a table that are meaningful for some purpose.
-- this will return a new instance of a 'player' table each time you call it.
-- if you need to add or remove attributes, you only need to do it in one place.
function getPlayerTable()
return {FirstName = "", LastName = ""}
end
local players = {}
local player = getPlayerTable()
player.FirstName = "Comp_uter15776"
player.LastName = "maciozo"
table.insert(players, player)
... more code to add players ...
local specific_player = players[1]
local specific_playerName = specific_player.FirstName..
" ".. specific_player.LastName
InputConsole("msg Some message ".. specific_playerName)

help with oauthService and linkedin

I am trying to iterate over a list of parameters, in a grails controller. when I have a list, longer than one element, like this:
[D4L2DYJlSw, 8OXQWKDDvX]
the following code works fine:
def recipientId = params.email
recipientId.each { test->
System.print(test + "\n")
}
The output being:
A4L2DYJlSw
8OXQWKDDvX
But, if the list only has one item, the output is not the only item, but each letter in the list. for example, if my params list is :
A4L2DYJlSwD
using the same code as above, the output becomes:
A
4
L
2
D
Y
J
l
S
w
can anyone tell me what's going on and what I am doing wrong?
thanks
jason
I run at the same problem a while ago! My solution for that it was
def gameId = params.gameId
def selectedGameList = gameId.class.isArray() ? Game.getAll(gameId as List) : Game.get(gameId);
because in my case I was getting 1 or more game Ids as parameters!
What you can do is the same:
def recipientId = params.email
if(recipientId.class.isArray()){
// smtg
}else{
// smtg
}
Because what is happening here is, as soon as you call '.each' groovy transform that object in a list! and 'String AS LIST' in groovy means char_array of that string!
My guess would be (from what I've seen with groovy elsewhere) is that it is trying to figure out what the type for recipientId should be since you haven't given it one (and it's thus dynamic).
In your first example, groovy decided what got passed to the .each{} closure was a List<String>. The second example, as there is only one String, groovy decides the type should be String and .each{} knows how to iterate over a String too - it just converts it to a char[].
You could simply make recipientId a List<String> I think in this case.
You can also try like this:
def recipientId = params.email instanceof List ? params.email : [params.email]
recipientId.each { test-> System.print(test + "\n") }
It will handle both the cases ..
Grails provides a built-in way to guarantee that a specific parameter is a list, even when only one was submitted. This is actually the preferred way to get a list of items when the number of items may be 0, 1, or more:
def recipientId = params.list("email")
recipientId.each { test->
System.print(test + "\n")
}
The params object will wrap a single item as a list, or return the list if there is more than one.

Resources