This is a read-only snapshot of the ComputerCraft forums, taken in April 2020.
chriskevini's profile picture

[LUA] Is there a function that returns the longest string in a table?

Started by chriskevini, 10 August 2012 - 01:00 AM
chriskevini #1
Posted 10 August 2012 - 03:00 AM
HARP
DERP

As the title says:
" Is there a built-in function that returns the longest string in a table? "
Luanub #2
Posted 10 August 2012 - 04:00 AM
Not built in no. You will have to create your own. I'm at work and can't test anything and don't want to give you something that doesn't work so I won't give you an example. But basically you can use string.len() to return the length of the string then do the comparisons between the strings and return the one with the longest string.len().
KaoS #3
Posted 10 August 2012 - 08:54 AM
try this - as always not tested, apologies


function getlongest(input)
if type(input)~="table" then
print("1st parameter must be a table")
return nil
end
local temp={}
temp[1]=0
temp[2]=nil
for a,b in pairs(input) do
if string.len(;)/>/>>temp[1] then
temp[1]=string.len(:(/>/>
temp[2]=a
end
end
if temp[2]==nil then
print("table has no values")
return nil
else
return input[temp[2]]
end
end

and a quick question for the admins, why does the forum automatically capitalise a 'b' if it is placed between brackets?? it makes a lot of code wrong
Cranium #4
Posted 10 August 2012 - 02:39 PM
and a quick question for the admins, why does the forum automatically capitalise a 'b' if it is placed between brackets?? it makes a lot of code wrong
It's the thing with the smileys. the guy with sunglasses is a b with )
KaoS #5
Posted 10 August 2012 - 02:40 PM
lol, ahah… thanks for clarifying

and I forgot to add, if you just want to return the delimiter of the table by returning temp[2] instead of input[temp[2]]
chriskevini #6
Posted 10 August 2012 - 05:39 PM
Alright then, thanks guys, quick question though, is 'string.len(var)' same with '#var'?
KaoS #7
Posted 12 August 2012 - 07:53 AM
not exactly sure, I think #var behaves differently if it is a table or something, I don't use it any more as it doesn't work properly in a table, it is meant to return the number of values in the table but it only works if all delimeters are numbers and in ascending order so it must be

mytable={}
mytable[1]="slkn"
mytable[2]="dbnfd"
mytable[3]="sdkjnd"
but not

mytable={}
mytable["test"]="asfdg"
mytable["anotherone"]="dfhdn"

so I wrote my own

function getvalues(input)
if type(input)~="table" then
print("you must enter a table")
return nil
end
local count=0
for aa,bb in (input) do
count=count+1
end
return count
end

that's where I got the idea for your funtion
Cranium #8
Posted 12 August 2012 - 03:21 PM
It is different, since you are now trying to get the length of a number, which can't be done with that command.
KaoS #9
Posted 12 August 2012 - 03:26 PM
yeah but the concept is the same, loop through the values of the table and process them for the result