Comparing integer variables in LUA - lua

I'm getting a very strange error, when trying to compare 2 integer variables using LUA on Corona SDK.
Basically this is what i have
**jAnswer** -- is a variable set via jSON, the value can only be 0 or 1.
local function checkAnswer(answer)
if (answer == jAnswer ) then
print("Correct Answer")
print("Answer is = "..answer.." jAnswer = "..jAnswer)
else
print("Wrong Answer")
print("Answer is = "..answer.." jAnswer = "..jAnswer)
end
end
checkAnswer(1) -- Calling the Function Here
Heres the problem, even if a get a output like "Answer is = 1, jAnswer = 1", i still get the "Wrong Answer".

Basically, the jAnswer, was being seen as a String, so i just needed to convert the string to number, using a global class on lua named tonumber()
jAnswer = tonumber(jAnswer, 10) -- Convert using the decimal base
Thanks!

Related

Converting a String into Instance

So.. I'm trying to Convert A string into a Roblox instance, like removing the "" from the string
I've tried the loadstring() but its giving me the error loadstring() is not available
Example:
A = "Enum.Keycode.Up" to A = Enum.Keycode.Up
I would appreciate if anyone could help
If your Enum table is global, then you can access it via _G:
Enum = {Keycode={Up="Test"}}
local A = "Enum.Keycode.Up"
local function get_value(a)
local ret = _G
for v in a:gmatch("([^%.]+)") do
if not ret[v] then return nil end
ret = ret[v]
end
return ret
end
print (get_value(A)) -- Test

Simple LZW Compression doesnt work

I wrote simple class to compress data. Here it is:
LZWCompressor = {}
function LZWCompressor.new()
local self = {}
self.mDictionary = {}
self.mDictionaryLen = 0
-- ...
self.Encode = function(sInput)
self:InitDictionary(true)
local s = ""
local ch = ""
local len = string.len(sInput)
local result = {}
local dic = self.mDictionary
local temp = 0
for i = 1, len do
ch = string.sub(sInput, i, i)
temp = s..ch
if dic[temp] then
s = temp
else
result[#result + 1] = dic[s]
self.mDictionaryLen = self.mDictionaryLen + 1
dic[temp] = self.mDictionaryLen
s = ch
end
end
result[#result + 1] = dic[s]
return result
end
-- ...
return self
end
And i run it by:
local compressor = LZWCompression.new()
local encodedData = compressor:Encode("I like LZW, but it doesnt want to compress this text.")
print("Input length:",string.len(originalString))
print("Output length:",#encodedData)
local decodedString = compressor:Decode(encodedData)
print(decodedString)
print(originalString == decodedString)
But when i finally run it by lua, it shows that interpreter expected string, not Table. That was strange thing, because I pass argument of type string. To test Lua's logs, i wrote at beggining of function:
print(typeof(sInput))
I got output "Table" and lua's error. So how to fix it? Why lua displays that string (That i have passed) is a table? I use Lua 5.3.
Issue is in definition of method Encode(), and most likely Decode() has same problem.
You create Encode() method using dot syntax: self.Encode = function(sInput),
but then you're calling it with colon syntax: compressor:Encode(data)
When you call Encode() with colon syntax, its first implicit argument will be compressor itself (table from your error), not the data.
To fix it, declare Encode() method with colon syntax: function self:Encode(sInput), or add 'self' as first argument explicitly self.Encode = function(self, sInput)
The code you provided should not run at all.
You define function LZWCompressor.new() but call CLZWCompression.new()
Inside Encode you call self:InitDictionary(true) which has not been defined.
Maybe you did not paste all relevant code here.
The reason for the error you get though is that you call compressor:Encode(sInput) which is equivalent to compressor.Encode(self, sInput). (syntactic sugar) As function parameters are not passed by name but by their position sInput inside Encode is now compressor, not your string.
Your first argument (which happens to be self, a table) is then passed to string.len which expects a string.
So you acutally call string.len(compressor) which of course results in an error.
Please make sure you know how to call and define functions and how to use self properly!

lua's loadstring() not working with tables

I have some text and I'm trying to load it via load string. The following works:
local m = loadstring("data = 5")()
But when the data is a table it doesn't work and gives the error "attempt to call a nil"
local m = loadstring("data = { 1 = 10}")()
The table declaration in lua require integer keys to be put inside square brackets:
data = {
[1] = value,
}
The enclosing of keys in square brackets is always allowed, valid and possible. It can be skipped iff your key follows the pattern: [A-Za-z_][A-Za-z0-9_]* (which is the same as a valid variable name in lua)
If you had added an assert you would have got a more helpful message:
local m = assert (loadstring("data = { 1 = 10}"))()
Result:
stdin:1: [string "data = { 1 = 10}"]:1: '}' expected near '='
stack traceback:
[C]: in function 'assert'
stdin:1: in main chunk
[C]: ?
And to actually answer the question, unless the table key happens to follow Lua variable naming rules, you have to put it inside square brackets, eg.
local m = assert (loadstring("data = { [1] = 10}"))()
m is still nil when I do this
What does that matter? The loadstring is done.
Just do this:
assert (loadstring("data = { 1 = 10}"))()
print (data [1])
You don't need the variable m. The loadstring puts a table into data - that is the important thing.

How to put floating points in LUA [duplicate]

I'd like to format a number to look like 1,234 or 1,234,432 or 123,456,789, you get the idea. I tried doing this as follows:
function reformatint(i)
local length = string.len(i)
for v = 1, math.floor(length/3) do
for k = 1, 3 do
newint = string.sub(mystring, -k*v)
end
newint = ','..newint
end
return newint
end
As you can see, a failed attempt, my problem is that I can't figure out what the error is because the program I am running this in refuses to report an error back to me.
Here's a function that takes negative numbers, and fractional parts into account:
function format_int(number)
local i, j, minus, int, fraction = tostring(number):find('([-]?)(%d+)([.]?%d*)')
-- reverse the int-string and append a comma to all blocks of 3 digits
int = int:reverse():gsub("(%d%d%d)", "%1,")
-- reverse the int-string back remove an optional comma and put the
-- optional minus and fractional part back
return minus .. int:reverse():gsub("^,", "") .. fraction
end
assert(format_int(1234) == '1,234')
assert(format_int(1234567) == '1,234,567')
assert(format_int(123456789) == '123,456,789')
assert(format_int(123456789.1234) == '123,456,789.1234')
assert(format_int(-123456789.) == '-123,456,789')
assert(format_int(-123456789.1234) == '-123,456,789.1234')
assert(format_int('-123456789.1234') == '-123,456,789.1234')
print('All tests passed!')
Well, let's take this from the top down. First of all, it's failing because you've got a reference error:
...
for k = 1, 3 do
newint = string.sub(mystring, -k*v) -- What is 'mystring'?
end
...
Most likely you want i to be there, not mystring.
Second, while replacing mystring with i will fix the errors, it still won't work correctly.
> =reformatint(100)
,100
> =reformatint(1)
,000
That's obviously not right. It seems like what you're trying to do is go through the string, and build up the new string with the commas added. But there are a couple of problems...
function reformatint(i)
local length = string.len(i)
for v = 1, math.floor(length/3) do
for k = 1, 3 do -- What is this inner loop for?
newint = string.sub(mystring, -k*v) -- This chops off the end of
-- your string only
end
newint = ','..newint -- This will make your result have a ',' at
-- the beginning, no matter what
end
return newint
end
With some rework, you can get a function that work.
function reformatint(integer)
for i = 1, math.floor((string.len(integer)-1) / 3) do
integer = string.sub(integer, 1, -3*i-i) ..
',' ..
string.sub(integer, -3*i-i+1)
end
return integer
end
The function above seems to work correctly. However, it's fairly convoluted... Might want to make it more readable.
As a side note, a quick google search finds a function that has already been made for this:
function comma_value(amount)
local formatted = amount
while true do
formatted, k = string.gsub(formatted, "^(-?%d+)(%d%d%d)", '%1,%2')
if (k==0) then
break
end
end
return formatted
end
You can do without loops:
function numWithCommas(n)
return tostring(math.floor(n)):reverse():gsub("(%d%d%d)","%1,")
:gsub(",(%-?)$","%1"):reverse()
end
assert(numWithCommas(100000) == "100,000")
assert(numWithCommas(100) == "100")
assert(numWithCommas(-100000) == "-100,000")
assert(numWithCommas(10000000) == "10,000,000")
assert(numWithCommas(10000000.00) == "10,000,000")
The second gsub is needed to avoid -,100 being generated.
I remember discussing about this in the LÖVE forums ... let me look for it...
Found it!
This will work with positive integers:
function reformatInt(i)
return tostring(i):reverse():gsub("%d%d%d", "%1,"):reverse():gsub("^,", "")
end
On the link above you may read details about implementation.

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