Hi,
Cryogenical wrote:What's the difference between using ipairs and pairs?
The difference lies in the way Lua treats tables: array-like or map-like. "Ipairs" will let you iterate on all values in the array part of a table, while "pairs" will go through all the values inside this table, being in the array part and the hash part.
I remeber I wrote recently a lengthy post on it, that you can find
here. The part titled "Tables" is all relevant to you, I believe. And it was written in a straightforward manner, so I hope it helps.
For more details, you can take a look at "What's the difference between pairs and ipairs ?" on
luafaq.
Now, concerning the initial issue, I think there are many ways to solve the problem. I can suggest one, though I am not advocating it is the best way. The Great DaedalusYoung cleverly mentionned it was not necessary to keep prefixes and suffixes for each entry in the songlist, since they were the same. I'll go with that, and treat then the songlist as a simple array:
Code: Select all
local songlist = { "song1", "song2", "song3",...}
In that respect, to sort all those songs in alphabetical order, i'll just write:
You can also have the following to format properly a songname to a path:
Code: Select all
local function wrapString(str, prefix, suffix)
return prefix..str..suffix
end
for _, songname in ipairs(songlist) do
print(wrapString(songname, "assets/music/", ".mp3"))
end
Another way to handle it is to keep the original table as-is, i.e store the full song path instead of the name only, and sort elements, but using pattern matching tricks to extract the songnames only and compare them. For instance, this:
Code: Select all
table.sort(songlist, function (a, b)
local songnameA = a:match('.+/(.+)%.mp3$')
local songnameB = b:match('.+/(.+)%.mp3$')
return songnameA < songnameB
end)
Hope this helps!