I have already seen many threads with examples of how to do this, the problem is, I still can't do it.
All the examples have tables with extra data. For example somethings like this
lines = {
luaH_set = 10,
luaH_get = 24,
luaH_present = 48,
}
or this,
obj = {
{ N = 'Green1' },
{ N = 'Green' },
{ N = 'Sky blue99' }
}
I can code in a few languages but I'm very new to Lua, and tables are really confusing to me. I can't seem to work out how to adapt the code in the examples to be able to sort a simple table.
This is my table:
local players = {"barry", "susan", "john", "wendy", "kevin"}
I want to sort these names alphabetically. I understand that Lua tables don't preserve order, and that's what's confusing me. All I essentially care about doing is just printing these names in alphabetical order, but I feel I need to learn this properly and know how to index them in the right order to a new table.
The examples I see are like this:
local function cmp(a, b)
a = tostring(a.N)
b = tostring(b.N)
local patt = '^(.-)%s*(%d+)$'
local _,_, col1, num1 = a:find(patt)
local _,_, col2, num2 = b:find(patt)
if (col1 and col2) and col1 == col2 then
return tonumber(num1) < tonumber(num2)
end
return a < b
end
table.sort(obj, cmp)
for i,v in ipairs(obj) do
print(i, v.N)
end
or this:
function pairsByKeys (t, f)
local a = {}
for n in pairs(t) do table.insert(a, n) end
table.sort(a, f)
local i = 0 -- iterator variable
local iter = function () -- iterator function
i = i + 1
if a[i] == nil then return nil
else return a[i], t[a[i]]
end
end
return iter
end
for name, line in pairsByKeys(lines) do
print(name, line)
end
and I'm just absolutely thrown by this as to how to do the same thing for a simple 1D table.
Can anyone please help me to understand this? I know if I can understand the most basic example, I'll be able to teach myself these harder examples.
local players = {"barry", "susan", "john", "wendy", "kevin"}
-- sort ascending, which is the default
table.sort(players)
print(table.concat(players, ", "))
-- sort descending
table.sort(players, function(a,b) return a > b end)
print(table.concat(players, ", "))
Here's why:
Your table players is a sequence.
local players = {"barry", "susan", "john", "wendy", "kevin"}
Is equivalent to
local players = {
[1] = "barry",
[2] = "susan",
[3] = "john",
[4] = "wendy",
[5] = "kevin",
}
If you do not provide keys in the table constructor, Lua will use integer keys automatically.
A table like that can be sorted by its values. Lua will simply rearrange the index value pairs in respect to the return value of the compare function. By default this is
function (a,b) return a < b end
If you want any other order you need to provide a function that returs true if element a comes befor b
Read this https://www.lua.org/manual/5.4/manual.html#pdf-table.sort
table.sort
Sorts the list elements in a given order, in-place, from list[1] to
list[#list]
This example is not a "list" or sequence:
lines = {
luaH_set = 10,
luaH_get = 24,
luaH_present = 48,
}
Which is equivalent to
lines = {
["luaH_set"] = 10,
["luaH_get"] = 24,
["luaH_present"] = 48,
}
it only has strings as keys. It has no order. You need a helper sequence to map some order to that table's element.
The second example
obj = {
{ N = 'Green1' },
{ N = 'Green' },
{ N = 'Sky blue99' }
}
which is equivalent to
obj = {
[1] = { N = 'Green1' },
[2] = { N = 'Green' },
[3] = { N = 'Sky blue99' },
}
Is a list. So you could sort it. But sorting it by table values wouldn't make too much sense. So you need to provide a function that gives you a reasonable way to order it.
Read this so you understand what a "sequence" or "list" is in this regard. Those names are used for other things as well. Don't let it confuse you.
https://www.lua.org/manual/5.4/manual.html#3.4.7
It is basically a table that has consecutive integer keys starting at 1.
Understanding this difference is one of the most important concepts while learning Lua. The length operator, ipairs and many functions of the table library only work with sequences.
This is my table:
local players = {"barry", "susan", "john", "wendy", "kevin"}
I want to sort these names alphabetically.
All you need is table.sort(players)
I understand that LUA tables don't preserve order.
Order of fields in a Lua table (a dictionary with arbitrary keys) is not preserved.
But your Lua table is an array, it is self-ordered by its integer keys 1, 2, 3,....
To clear up the confusing in regards to "not preserving order": What's not preserving order are the keys of the values in the table, in particular for string keys, i.e. when you use the table as dictionary and not as array. If you write myTable = {orange="hello", apple="world"} then the fact that you defined key orange to the left of key apple isn't stored. If you enumerate keys/values using for k, v in pairs(myTable) do print(k, v) end then you'd actually get apple world before orange hello because "apple" < "orange".
You don't have this problem with numeric keys though (which is what the keys by default will be if you don't specify them - myTable = {"hello", "world", foo="bar"} is the same as myTable = {[1]="hello", [2]="world", foo="bar"}, i.e. it will assign myTable[1] = "hello", myTable[2] = "world" and myTable.foo = "bar" (same as myTable["foo"]). (Here, even if you would get the numeric keys in a random order - which you don't, it wouldn't matter since you could still loop through them by incrementing.)
You can use table.sort which, if no order function is given, will sort the values using < so in case of numbers the result is ascending numbers and in case of strings it will sort by ASCII code:
local players = {"barry", "susan", "john", "wendy", "kevin"}
table.sort(players)
-- players is now {"barry", "john", "kevin", "susan", "wendy"}
This will however fall apart if you have mixed lowercase and uppercase entries because uppercase will go before lowercase due to having lower ASCII codes, and of course it also won't work properly with non-ASCII characters like umlauts (they will go last) - it's not a lexicographic sort.
You can however supply your own ordering function which receives arguments (a, b) and needs to return true if a should come before b. Here an example that fixes the lower-/uppercase issues for example, by converting to uppercase before comparing:
table.sort(players, function (a, b)
return string.upper(a) < string.upper(b)
end)
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"))
Consider the following code:
#!/usr/bin/lua
local field =
{
name = '',
array = {},
new = function(self, o)
o = o or {}
setmetatable(o, self)
self.__index = self
return o
end,
}
local fld1 = field:new()
local fld2 = field:new()
fld1.name = 'hello'
table.insert(fld1.array, 1)
table.insert(fld1.array, 2)
table.insert(fld1.array, 3)
fld2.name = 'me'
table.insert(fld2.array, 4)
table.insert(fld2.array, 5)
print('fld1: name='..fld1.name..' len='..#fld1.array)
print('fld2: name='..fld2.name..' len='..#fld2.array)
The output when executed is as follows:
fld1: name=hello len=5
fld2: name=me len=5
From the output, it can be seen that name has different values in fld1 and fld2. array, however, has the same value in fld1 and fld2 (fld1.array and fld2.array are the same and therefore have the same length of 5).
How do I fix this code so that fld1.array is independent of fld2.array (so that modifying fld1.array does not change fld2.array)?
First off, fld1 and fld2 have distinct names because you gave them distinct names - their own properties.
When you perform table key assignment the new key and value are stored directly in the table that you specify. The __index metamethod only comes in to play when you perform table key lookup and the key is not found in the table.
A quick example where we can see that table key assignment will shadow keys in the __index lookup chain.
local Foo = { shared = 'shared', private = 'private' }
Foo.__index = Foo
local foo = setmetatable({}, Foo)
foo.private = 'a shadowed value'
print(Foo.shared, foo.shared) -- shared shared
print(Foo.private, foo.private) -- private a shadowed value
Note: there is a __newindex metamethod for catching table key assignment that involves a never-before-seen key.
Consider treating the new method more like a traditional constructor function, wherein you assign 'private' properties to newly created instances.
local Field = {
-- shared properties go here
}
-- shared methods are defined as such
function Field:new (name)
local o = {
-- private properties for the newly created object go here
name = name or '',
array = {}
}
self.__index = self
return setmetatable(o, self)
end
function Field:insert (value)
table.insert(self.array, value)
end
local fld1 = Field:new('hello')
local fld2 = Field:new('me')
fld1:insert(1)
fld1:insert(2)
fld1:insert(3)
fld2:insert(4)
fld2:insert(5)
print('fld1: name='..fld1.name..' len='..#fld1.array) -- fld1: name=hello len=3
print('fld2: name='..fld2.name..' len='..#fld2.array) -- fld2: name=me len=2
Some more notes:
Generally, 'class' names should be in PascalCase, to make them distinct.
Having a :new function in the lookup chain means instances can invoke it, this may or may not be desirable. (Can create slightly ugly inheritance this way.)
There is a difference between how you define methods which use the implicit self. You should give Chapter 16 of Programming in Lua a read. It might be a tad dated if you're using 5.2 or 5.3, but it should still have a lots of useful information.
If you're interested in a tiny library for this, I recently wrote Base. If you look around, you'll find lots of little OOP packages for making these kinds of things a bit easier.
Lua's oop technic not same c++, java
__index metamethod reference target table record.
and so, fld1, fld2 array item is Field's array item.
you must make a new table and use it.
why name's value different. Because, Your assign a name
fld1.name = 'hello'
simply code fix
fld1.array = {}
using new method code fix
local o1 = {name = '', array = {}}
local o2 = {name = '', array = {}}
local fld1 = field:new(o1)
local fld2 = field:new(o2)
make new table(make o) and insert new method.
I realize this is usually not a great practice, but how would I use a string containing an integer (e.g. "7") as a table key? For example:
local myTable = {
"1" = "Foo",
"2" = "Bar"
}
If memory serves from reading the Lua manual back in the day, that should be possible with some special syntax, but what I've written above is a syntax error.
Like this:
local myTable = {
["1"] = "Foo",
["2"] = "Bar"
}
Because the keys are not valid identifiers, you can't use the syntax sugar form.
Backpack = {Potion = 'backpack',Stack = 'bag',Loot = 'derp', Gold = 'random'}
Backpack[1] ~= 'backpack' -- nope
As you guys can see, I cannot call Backpack[1] since its not a numeral table, how would I generate a table after the construction of Backpack, consisting only of it's values? for example:
Table_to_be_Constructed = {Value of Potion,Value of Stack,Value of Loot,Value of Gold} -- this is what i need
It seems simple but I couldn't find a way to do it.
I need it this way because i will run a numeric loop on Table_to_be_Constructed[i]
To iterate over all the key-value pairs in a table, use the pairs function:
local Table_to_be_Constructed = {}
for key, value in pairs(Backpack) do
table.insert(Table_to_be_Constructed, value)
end
Note: the iteration order is not defined. So, you might want to sort Table_to_be_Constructed afterwards.
By convention, the variable name _ is used to indicate a variable who's value won't be used. So, since you want only the values in the tables, you might write the loop this way instead:
for _, value in pairs(Backpack) do
For the updated question
Backpack has no order (The order in the constructor statement is not preserved.) If you want to add an order to its values when constructing Table_to_be_Constructed, you can do it directly like this:
local Table_to_be_Constructed = {
Backpack.Potion,
Backpack.Stack,
Backpack.Loot,
Backpack.Gold
}
Or indirectly like this:
local items = { 'Potion', 'Stack', 'Loot', 'Gold' }
local Table_to_be_Constructed = {}
for i=1, #items do
Table_to_be_Constructed[i] = Backpack[items[i]]
end