Lua Problems with Arguments - lua

What's wrong with this lua code, my argument is never converted to a number or recognized as a number no matter what I type?
I tried "distance = tonumber(arg[0]) or 0" as well.
--Args
local args = {...}
--Variables
local distance = 0
if #args > 0 and type(args[0])=="string" then args[0] = tonumber(args[0]) end
if #args > 0 and type(args[0])=="number" then distance = args[0] end
print("Distance: "..distance)

Lua uses 1-based indices for its arrays. args[0] is nil, and therefore has the type "nil".
By the way, this condition is entirely unnecessary. tonumber will check to see if its argument is a number and simply return it if needed. It will return nil if the argument cannot be converted to a number. So just use:
distance = tonumber(args[1])
You don't even need to check the length of args; if no arguments were provided, it will be nil, and tonumber will return nil. Thus, just check to see if distance is nil.

Related

How to check if value is string in lua?

Hello guys i please need your help.
I have values, most of them are numbers but some of them are strings.
How can i check if value is string or number?
I already tried this code but when it reach string value i get error " attempt to perform arithmetic on local 'numberValue' (a nil value)"
function Config:IsNumber(value)
if value ~=nill or value ~=nil then
local numberValue = tonumber(value)
if numberValue/numberValue ==1 then
return true
else
return false
end
end
end
end
end
First of all let's start with errors in your code.
You have 2 ends to many.
it is nil, not nill. I'm not sure where you're going with that check.
Other issues / things to improve:
numberValue / numberValue == 1 does not make any sense. A number dividided by itself always results in 1. So checking that is pointless.
Also instead of
if something == 1 then
return true
else
return false
end
Can simply be replaced by return something == 1. There is no need for a conditional statement here.
To your question:
To check wether a value is a string use type(value) == "string".
To check wether a value can be convertet do a number use tonumber(value). It will either return a number or nil.
So according to your error the conversion to a number failed.
If you don't know for sure that your value can be converted to a number, you should ensure that tonumber succeded befor you do any operations on its return value.
local numberValue = tonumber(value)
if not numberValue then
print("converting value to a number failed)
return
end
-- at this point you know numberValue is a number
So if you wanted to write a function that ensures a string represents a number you could do something like this:
function IsNumber(value)
return tonumber(value) and true or false
end

How to check only numbers in value - Lua

I want to make sure players can't put letters or symbols in the value, how do I check if it is a number only?
function seed1()
ESX.UI.Menu.CloseAll()
ESX.UI.Menu.Open('dialog', GetCurrentResourceName(), 'amountseed1', {
title = 'Shop'
}, function(data, menu)
local amount = tostring(data.value)
if amount == nil then
...
else
[[What should i put here to check its only contain number ?]]
end
end, function(data, menu)
menu.close()
end)
end
I can put something like this, but maybe this isn't a good way to do that:
else
if amount > 0 and amount < 9999 then
...
else
print('Invalid amount or amount higher than 9999')
end
end
Since you only care about the number, there is no need to convert the value to string:
local amount = tostring(data.value)
-- ^^^^^^^^ partially useless
Instead, go for the number right away:
local amount = tonumber(data.value)
if amount == nil then
-- Not a number
else
-- A number
end
In the end, remember that tonumber attempts to convert the value to a number and returns nil in case of a failure.
Simply replace tostring with tonumber. This will turn strings into numbers if possible, and return nil if it can't.
Keep in mind: tonumber won't just take the largest valid prefix of a string, so tonumber("20 foo") will return nil and not 20. It also supports all ways to write number literals in Lua, so tonumber("2.3e2") will return 230 and tonumber("0xff") will return 255.

How can i check if strings are equal without using the eq operator ( == / ~=)

my idea is the convert the 2 strings into byte, subtract and then check if they're 0 using a for loop like this
function match(str1, str2, callback)
local res = string.byte(str1) - string.byte(str2)
for i = 1, res(0) do
spawn(callback)
end
end
but that just doesn't work can anyone write me a code would appreciate...
rawequal(str1, str2) -- Compares two values without calling any metamethods

How can a Lua function return nil, even if the returned value is not nil inside the function?

I have created a function that (pseudo)randomly creates a table containing numbers. I then loop this function until at least correct result is found. As soon as I've confirmed that at least one such result exists, I stop the function and return the table.
When I create tables containing small values, there are no issues. However, once the random numbers grow to the range of hundreds, the function begins to return nil, even though the table is true the line before I return it.
local sort = table.sort
local random = math.random
local aMin, aMax = 8, 12
local bMin, bMax = 200, 2000
local function compare( a, b )
return a < b
end
local function getNumbers()
local valid = false
local numbers = {}
-- Generate a random length table, containing random number values.
for i = 1, random( aMin, aMax ) do
numbers[i] = random( bMin, bMax )
end
sort( numbers, compare )
-- See if a specific sequence of numbers exist in the table.
for i = 2, #numbers do
if numbers[i-1]+1 == numbers[i] or numbers[i-1] == numbers[i] then
-- Sequence found, so stop.
valid = true
break
end
end
for i = 1, #numbers-1 do
for j = i+1, #numbers do
if numbers[j] % numbers[i] == 0 and numbers[i] ~= 1 then
valid = true
break
end
end
end
if valid then
print( "Within function:", numbers )
return numbers
else
getNumbers()
end
end
local numbers = getNumbers()
print( "Outside function:", numbers )
This function, to my understanding, is supposed to loop infinitely until I find a valid sequence. The only way that the function can even end, according to my code, is if valid is true.
Sometimes, more often than not, with large numbers the function simply outputs a nil value to the outside of the function. What is going on here?
You're just doing getNumbers() to recurse instead of return getNumbers(). This means that if the recursion gets entered, the final returned value will be nil no matter what else happens.
In the else case of the if valid then, you are not returning anything. You only return anything in the valid case. In the else case, a recursive call may return something, but then you ignore that returned value. The print you see is corresponding to the return from the recursive call; it isn't making it out the original call.
You mean to return getNumbers().

lua overload: possibilities?

My group is currently working with Lua,creating an android game. One thing we've run into is the appearant inability to create overload constructors.
I'm used to having an object set up with default values, that then get overloaded if need be.
ex:
apples()
{
taste="yum";
amount = 0;
}
apples(string taste, int num)
{
taste=taste;
amount=num;
}
However, with the inability to do that, we have these lare if/else sections for initialization that look like this
if velX ~= nil then
self.velX = velX
else
self.velX = 0
end
if velY ~= nil then
self.velY = velY
else
self.velY = 0
end
Is there a better way to set this up in Lua?
Instead of using if/else statements, you can initialize your variables with a condition providing the default value.
function apples(taste, num)
taste = taste or "yum"
amount = num or 0
-- ...
end
Lua's or operator evaluates and returns its first operand unless it is nil or false, otherwise it evaluates and returns its second operand. That leads to the above idiom for default values.

Resources