Attempt to perform arithmetic on field 'duration' (a string value) [duplicate] - lua

This question already has an answer here:
Lua: attempt to perform arithmetic on a string value
(1 answer)
Closed 5 years ago.
Here is my error message:
Panel: [name:DItemSlot][class:Panel][138,69,64,64]
[ERROR] addons/pointshop2/lua/ps2/client/notifications/cl_knotificationpanelmanager.lua:91: attempt to perform arithmetic on field 'duration' (a string value)
1. unknown - addons/pointshop2/lua/ps2/client/notifications/cl_knotificationpanelmanager.lua:91
And here is my code:
if not self.panelSlidingIn and #self.notificationsWaiting > 0 then
self.panelSlidingIn = table.remove( self.notificationsWaiting, 1 ) --
Dequeue
self.panelSlidingIn:SetParent( self )
self.panelSlidingIn:SetVisible( true )
self.panelSlidingIn.slideOutStart = CurTime( ) +
self.panelSlidingIn.duration + self.slideInDuration
self.slidingStarted = CurTime( )
table.insert( self.notifications, self.panelSlidingIn )
surface.PlaySound( self.panelSlidingIn.sound or
"kreport/misc_menu_4.wav" )
end
I don't know what is happening, and I can't seem to fix it either.

When you use + operator on string Lua tries to convert them to numbers. If it couldn't it gives you such errors. If you want to concatinate strings use operator .. instead. If you want to make arithmetics, make sure strings have convertable values.
Similar question: here.

Related

LUA Error attempt to compare number to nil [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 2 years ago.
Improve this question
Need help with code that generates lots of errors:
function()
local restedxp = GetXPExhaustion()
local totalXP = UnitXPMax("player")
local percent = 0
if restedxp > 0 then percent = floor((restedxp / totalXP) * 100) end
local ret = string.format("%s%%", percent)
return ret
end
Error: attempt to compare number to nil
Comparing a number vs nil doesn't make sense. Hence the error.
In your case you only have one comparison in the provided code which is any expression with a relational operator.
The usual thing you do is to find out which of the two values is nil and fix the reason or if you can't avoid that value being nil make sure you only do the comparison if it is not.
In your case this is pretty simple. You go to the line number which is given in the error message. You find the only conditional expression restedxp > 0 and as 0 is obviously a number it must be restedxp that is nil
You find out where restedxp is assigned the last value befor the comparison which is
local restedxp = GetXPExhaustion()
So GetXPEhaustion() returns nil!
If you have access to that function you may be able to fix it or at least find out if you can do anything so it won't return nil!
If you can't you either assign a default value to restedxp, for example 0.
local restedxp = GetXPExhaustion() or 0
Or you avoid to compare the values with a conditional statement.
if type(restedxp) == "number" and restedxp > 0 then
percent = restedXp // totalXP * 100
end
Or if you know restedxp is either a number or nil
if restedxp and restedxp > 0 then
percent = restedXp // totalXP * 100
end
The same makes sense for totalXP of course. Just also make sure it isn't 0 befor you divide.
Your string formatting is incorrect btw.
percent is a number so you should use %d instead of %s as %s refers to a string. It will work as Lua will convert your number to a string but it's not very clean.
https://www.lua.org/manual/5.3/manual.html#pdf-string.format
Option s expects a string; if its argument is not a string, it is
converted to one following the same rules of tostring. If the option
has any modifier (flags, width, length), the string argument should
not contain embedded zeros.

Result values in '? :' expression have mismatching types '()' and 'Bool' [duplicate]

This question already has answers here:
Swift ternary operator compilation error
(2 answers)
Closed 6 years ago.
I have an array of Doubles, and a button which when pressed empties the array. I want the button to be enabled only when the count of the array is greater than zero. The code is the following:
var numbers: [Double] = [] //At some point I add some numbers here
numbers.count > 0 ? deleteAllNumbersButton.isEnabled = true : deleteAllNumbersButton.isEnabled = false
The compiler complains:
Result values in '? :' expression have mismatching types '()' and
'Bool'
When put in an if statement it works just fine though. I can't understand the issue here. Has anyone seen this before? I use XCode 8.2.1 and Swift 3.
Note, I don't know Swift, but this doesn't appear to be a Swift specific problem. I can't explain the exact error, but I can show you how to write it properly.
Conditional expressions are used almost exclusively when you need to assign something to a variable or return a value, and have exactly 2 options to choose from.
This is what you're trying to do, but you've written it in a convoluted way that's likely confusing the compiler.
In the expression:
numbers.count > 0 ? deleteAllNumbersButton.isEnabled = true
: deleteAllNumbersButton.isEnabled = false
Because the "then" and "else" expressions both contain assignments, they evaluate (I'm assuming) to a Unit (())/"void". I'm guessing this is why it's yelling at you. It never makes sense to use a ternary to return a Unit (Actually, as noted in the comments, operator precedence is the real reason for the error).
What you likely meant was:
deleteAllNumbersButton.isEnabled = numbers.count > 0 ? true : false
Notice how instead of assigning in the conditional expression, the result of the expression is instead assigned. In cases that can't be simplified further (see below), this is how conditional expressions should be used.
This new form should raise red flags though. Why have the conditional expression evaluate to true/false? That's almost always a code smell. It's redundant given the condition already evaluates to a Boolean value.
Just reduce it down to:
deleteAllNumbersButton.isEnabled = numbers.count > 0

Lua Text and function print in the same line [closed]

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 6 years ago.
Improve this question
Can any body help me ?
function sum(_g, _h)
local num = (_g * _h) / 2
return num
end
print("The result is")(sum(10, 6))
Why this isn't working ?
The function print takes one or more strings as arguments.
When the strings are entered as different arguments, it outputs them separated by a tab
The result is 20
To get this output, just imagine you store the return from sum in a variable
res = sum(10, 6)
And then call print entering your string and the result just like you enter 10 and 6 in your function sum:
print("The result is ", res)
This also traduces to
print("The result is ", sum(10, 6))
Without needing to store the result anywhere.
Anyway if you target an output which looks like
The result is 20
you must enter only one string as the argument for print
..
is the operator which lets you concatenate two string in one string, so that "hello".." world" results in "hello world".
Now just combine the two strings "The result is " and 20 (which actually is a number, but it gets automatically converted to a string) with the .. operator, as in
res = sum(10, 6)
mystring = "The result is "
print(mystring..res)
Or, more shortly
print("The result is "..sum(10, 6))

Lua table initialization - what is incorrect here [duplicate]

This question already has an answer here:
lua: iterate through all pairs in table
(1 answer)
Closed 8 years ago.
I am trying to initialize and print a table. It just isnt working. Any idea what is wrong with this code?
--!/usr/bin/env lua
local retv = {}
retv["test"] = 1000
for k,v in ipairs(retv) do
print (k,v)
end
It prints nothing. I am sure I am missing something very basic but I cant figure this out.
There are two forms of the for-loop in Lua:
The numeric and the generic for-loop.
ipairs(t) is an iterator constructor returning up to three arguments suitable for the generic for, allowing you to iterate over the initial sequence (indices 1,2,3,...) in order.
Possible implementations:
function ipairs(t)
local i = 0
return function()
i = i + 1
if t[i] ~= nil then
return i, t[i]
end
end
end
local function ipairs_helper(t, i)
i = i + 1
if t[i] ~= nil then
return i, t[i]
end
end
function ipairs(t)
return ipairs_helper, t, 0
end
As you can see, that will never return your entry with key "test".
What you want instead, is pairs(t), which is equivalent to next, t.
That will iterate all elements.
You need to use pairs instead of ipairs. pairs iterates over all keys, ipairs only iterates over keys that form a sequence of integers starting from 1 without gaps. (Whether these keys are stored in the array or the hash part of the table is an implementation detail and may change during the lifetime of the table.)
For example, ipairs({'a', 'b', nil, 'c'}) iterates over keys 1 and 2, stopping at (and not including) 3, as that key is missing from the table.

Find the string length of a Lua number?

Easy question here, probably, but searching did not find a similar question.
The # operator finds the length of a string, among other things, great. But with Lua being dynamically typed, thus no conversion operators, how does one type a number as a string in order to determine its length?
For example suppose I want to print the factorials from 1 to 9 in a formatted table.
i,F = 1,1
while i<10 do
print(i.."! == "..string.rep("0",10-#F)..F)
i=i+1
F=F*i
end
error: attempt to get length of global 'F' (a number value)
why not use tostring(F) to convert F to a string?
Alternatively,
length = math.floor(math.log10(number)+1)
Careful though, this will only work where n > 0!
There are probably a dozen ways to do this. The easy way is to use tostring as Dan mentions. You could also concatenate an empty string, e.g. F_str=""..F to get F_str as a string representation. But since you are trying to output a formatted string, use the string.format method to do all the hard work for you:
i,F = 1,1
while i<10 do
print(string.format("%01d! == %010d", i, F))
i=i+1
F=F*i
end
Isn't while tostring(F).len < 10 do useful?

Resources