lua overload: possibilities? - lua

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.

Related

Lua math.random explain

sorry for asking this question but I couldn't understand it
-- but i don't understand this code
ballDX = math.random(2) == 1 and 100 or -100
--here ballDY will give value between -50 to 50
ballDY = math.random(-50, 50)
I don't understand the structure what is (2) and why it's == 1
Thank you a lot
math.random(x) will randomly return an integer between 1 and x.
So math.random(2) will randomly return 1 or 2.
If it returns 1 (== 1), ballDX will be set to 100.
If it returns 2 (~= 1), ballDX will be set to -100.
A simple way to make a 50-50 chance.
That is a very common way of assigning variables in Lua based on conditionals. It’s the same you’d do, for example, in Python with “foo = a if x else b”:
The first function, math.random(2), returns either 1 or 2. So, if it returns 1 the part math.random(2) == 1 is true and so you assign 100 to the variable ballDX. Otherwise, assign -100 to it.
In lua
result = condition and first or second
basically means the same as
if condition and first ~= nil and first ~= false then
result = first
else
result = second
end
So in your case
if math.random(2) == 1 then
ballDX = 100
else
ballDX = -100
end
in other words, there is a 50/50 chance for ballDX to become 100 or -100
For a better understanding, a look at lua documentation helps a lot :
https://www.lua.org/pil/3.3.html
You can read:
The operator or returns its first argument if it is not false; otherwise, it returns its second argument:
So if the random number is 1 it will return the first argument (100) of the "or" otherwise it will return the second argument (-100).

Computercraft function that returns an array, use first element for boolean

Edited for more details:
I'm trying to have a turtle that is sitting in front of a sapling wait for it to grow before cutting it down. It compares the log to the item in front until it matches. The system I'm currently using works, but I was hoping there was a slightly more minimal way to write it.
checkTarget = {
forward = function(tgt)
check = {turtle.inspect()} --creates table with first as boolean, second as information table
local rtn = {false, check[2]}
if type(tgt) == "table" then
for k, v in pairs(tgt) do
if check[2].name == v then
rtn = {true, v}
break
end
end
elseif tgt == nil then
return check[1]
elseif check[2].name == tgt then
rtn[1] = true
end
return rtn
end,--continued
This takes an argument, either a string or an array of strings, to compare against. When it checks the block in front it saves the detailed information to the second element in rtn and the first to a default of false. If the string matches the checked block's name, then it changes rtn[1] to true and returns all of it, which is the table at the bottom when doing checkTarget.forward("minecraft:log").
My question was, I am currently making a disposable variable to store the array that is returned from checkTarget, and then calling the variable's first element to get if it's true or not. I was hoping there was a way to include it in the if statement without the disposable variable (tempV)
repeat
local tempV = fox.checkTarget.forward("minecraft:log")
if tempV[1] then
cut()
fox.goTo({x = 0, y = 0, z = 0})
fox.face(0)
end
tempV = fox.checkTarget.forward("minecraft:log")
until not run
{
false,
{
state = {
stage = 0,
type = "birch",
},
name = "minecraft:sapling",
metadata = 2
}
}
Instead of
local tempV = fox.checkTarget.forward("minecraft:log")
if tempV[1] then
end
You can do
if fox.checkTarget.forward("minecraft:log")[1] then
end
and then calling the variable's first element to get if it's true or
not.
With tempV[1] you're not calling the first element, you're indexing it.
To call something you have to use the call operator () which doesn't make sense as a boolean is not callable.

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().

Computercraft Lua change nil to 0

I am using Computercraft, a Minecraft mod, and I needed help with something. I am attempting to find all peripherals of a type, get the energy from them, and add them together. However, I get a "attempt to perform arithmetic on nill" or something error. Here is my code:
local periList = peripheral.getNames()
energy = 0
totalenergy = 0
for i = 1, #periList do
if peripheral.getType(periList[i]) == "cofh_thermalexpansion_energycell" then
local cell = peripheral.wrap(periList[i])
print(periList[i])
if cell.getEnergyStored("potato") ~= "nil" then
energy = cell.getEnergyStored("potato")
print(cell.getEnergyStored("potato"))
else
energy = 0
print(0)
end
totalenergy = totalenergy + energy
end
end
print(totalenergy)
Sorry, codebox didn't work
Anyways, does anyone know how to fix this?
nil and "nil" are two different things.
The former is the nil type "singleton" the latter is a string of three characters. They are not equivalent.
Try dropping the quotes from the if line.
Also you can assign (the potential) nil to energy and then directly energy and set it to 0 if it is nil (or even just use
energy = cell.getEnergyStored("potato") or 0
directly since nil is a "false-y" value so nil or 0 evaluates to 0).

Lua Problems with Arguments

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.

Resources