Here is the code im working with,
function Speedhack1()
boost = 1.5
if (readBytes('[_speed]') ~- nil) then
writeFloat ('[_speed]+DC', readFloat('[_speed]+DC')*boost)
writeFloat ('[_speed]+E0', readFloat('[_speed]+E0')*boost)
writeFloat ('[_speed]+E4', readFloat('[_speed]+E4')*boost)
end
end
createHotkey(Speedhack1, VK_UP)
function Speedhack2()
boost = 0.5
if (readBytes('[_speed]') ~- nil) then
writeFloat ('[_speed]+DC', readFloat('[_speed]+DC')*boost)
writeFloat ('[_speed]+E0', readFloat('[_speed]+E0')*boost)
writeFloat ('[_speed]+E4', readFloat('[_speed]+E4')*boost)
end
end
createHotkey(Speedhack2, VK_DOWN)
Ive defined speed and made pointers with the corresponding offsets my aob script to find speed works and the lua script gets executed but when pressing one of the hotkeys to start the function it gives me
Error:[string "function Speedhack1()
..."]:3: attempt to perform arithmetic on a nil value
if _speed has been defined and the offsets match i thought ~-nil would be the proper way to say "whatever the value is"
You probably meant to write ~= because ~- doesn't make much sense here. But it can also just be left out and you can write
if (readBytes('[_speed]')) then
This also checks whether it's not nil (or false)
Related
I'm new to this platform and I'm still learning to
program in Lua, so, if any newbie errors appear, forgive me.
The following code is from one of the functions in my project that reads the insert
of the user and validates whether or not it is a data of type "Number". If,
the loop will be broken and the function will return the user input, otherwise, the
program will ask the user to enter the data again:
function bin.readnum(text)
local insertion
if text == nil then text = "Text: " end
while (insertion == nil) do
insertion = nil
print(text)
insertion = io.read("number")
if insertion ~= nil then break end
end
return insertion
end
But, if the user enters a wrong data (string) the function prints the text
madly instead of asking the user to re-enter the data.
When io.read fails to parse the data it got into a number, it doesn't discard it, but instead leaves it in the buffer for the next call to it. That means that in your code, instead of letting the user enter something else, it'll just keep trying to parse the same non-number forever. To fix it, in your if insertion ~= nil then block, do io.read() right before break, to read and discard the whole invalid line.
In addition to what Joseph Sible said:
io.read("number") is wrong: 5.1 docs demand "*n" and 5.4 docs demand just "n" for reading numbers. It probably works nevertheless due to Lua just searching for the chars in the string.
I recommend just replacing insertion = io.read("number") withinsertion = tonumber(assert(io.read(), "EOF")) - this will read a line and try to parse it as a number; the assert gracefully deals with nil being returned by io.read for EOF.
You don't need to set insertion to nil, the later assignment will do that already if what was read is not a valid number.
Style: Consider replacing your explicit nil checks with truthiness checks and removing the parentheses around the while-condition. You don't need a break, you can immediately return the read number; finally, you can even replace the entire loop with tail recursion.
All in all I'd rewrite it as follows:
function bin.readnum(text)
print(text or "Text: ")
local num = tonumber(assert(io.read(), "EOF"))
if num then return num end
return bin.readnum(text)
end
or alternatively using a repeat-until loop:
function bin.readnum(text)
local num
repeat
print(text or "Text: ")
num = tonumber(assert(io.read(), "EOF"))
until num
return num
end
I'm new to Lua and trying to figure out how the return statement in the squares function below is being used in the following code snippet:
function squares(iteratorMaxCount)
return square,iteratorMaxCount,0
end
The square parameter in the return statement refers to a function with the following signature:
function square(iteratorMaxCount,currentNumber)
What's confusing me is that the return statement looks like it's returning three values. What I think it's actually doing, however, is passing iteratorMaxCount and 0 as the arguments to a square function call.
Can anyone explain to me what's happening with this syntax? How is this serving as a function call as opposed to returning three values? In my mind, it feels as though the return statement should be written return square(iteratorMaxCount, 0) as opposed to return square, iteratorMaxCount, 0. I know that this is obviously wrong, but I can't figure out why.
I've tried searching through the Lua Manual, Lua Reference Guide, and searching Google, but I can't seem to find anything that explains this particular syntax. Can anyone point me in the right direction, please?
Thanks in advance.
Full code below via
Tutorialspoint
function square(iteratorMaxCount,currentNumber)
if currentNumber<iteratorMaxCount
then
currentNumber = currentNumber+1
return currentNumber, currentNumber*currentNumber
end
end
function squares(iteratorMaxCount)
return square,iteratorMaxCount,0
end
for i,n in squares(3)
do
print(i,n)
end
squares really does return three values, the first of which is a function. squares does not call square at all.
The trick here is how the for ... in syntax works. In the Lua 5.3 Reference Manual, section 3.3.5 says:
A for statement like:
for var_1, ···, var_n in explist do block end
is equivalent to the code:
do
local f, s, var = explist
while true do
local var_1, ···, var_n = f(s, var)
if var_1 == nil then break end
var = var_1
block
end
end
So the keyword "in" needs to be followed by three values:
an "iterator function" for getting the variables in each iteration
a "state" value to pass to the function each time
an initial value to pass to the function the first time
After the first time the function is called, the first value from the previous call is passed back into the next function call. When the first value returned from the function is nil, the for loop ends.
So in this example, squares(max) is designed to be used after "in", using square as the iterator function, max as the "state", 0 as the initial value, and a number and its square as the loop data values.
I have a function in lua, which is given 2 vectors, return the lambda multiplier of first vector to second one, here is my code
function Math.vectorLambda( v1,v2 )
local v1Length,v2Length=math.sqrt(v1.x^2+v1.y^2),math.sqrt(v2.x^2+v2.y^2)
if v1Length==0 then
return nil
else
local dotProduct=v1.x*v2.x+v1.y*v2.y
print(dotProduct,v1Length,v2Length,math.abs(dotProduct)==(v1Length*v2Length))
if math.abs(dotProduct)==(v1Length*v2Length) then
if v1.x~=0 then
return v2.x/v1.x
else
return v2.y/v1.y
end
else
return nil
end
end
end
However, if
--this is what I get from terminal and I believe that it does not display the whole number--
v1={0.51449575542753,-0.85749292571254}
v2={-10,16.666666666667}
the output is
-19.436506316151 1 19.436506316151 false
which is saying the absolute value of dotProduct and v1Length*v2Length are not the same...
What is the reason for above, rather than I am blind? :(
BTW, the function is not stable..with exactly the same vectors, the function might has the same output except math.abs(dotProduct)==(v1Length*v2Length) gives true and hence return correct answer rather than nil, why?
Floats are tricky. You most likely have differences on the smaller decimal places (I don't know for sure, since I get true here). Try printing the numbers with a bigger precision, using a function like:
function prec_print(v, prec)
local format = '%.' .. prec .. 'f'
print(string.format(format, value))
end
In any case, you should almost never use == to compare floating point equality. For floats, it's quite easy to get false for simple things like a+b-b==a. What you should probably do is to check whether de difference of the two values is less than some threshold:
function almost_equal(float1, float2, threshold)
return math.abs(float1 - float2) <= threshold
end
But it's actually trickier than that (if, say, float1 and float2 are too far apart). Anyway, this read is mandatory for anyone working with floats: http://docs.oracle.com/cd/E19957-01/806-3568/ncg_goldberg.html
Cheers!
Im a amatuer at coding. So, mind me if i face palmed some things.
Anyways, im making a alpha phase for a OS im making right? I'm making my installer. Two questions. Can i get a code off of pastebin then have my lua script download it? Two. I put the "print" part of the code in cmd. I get "Illegal characters". I dont know what went wrong. Here's my code.
--Variables
Yes = True
No = False
--Loading Screen
print ("1")
sleep(0.5)
print("2")
sleep(0.5)
print("Dowloading OS")
sleep(2)
print("Done!")
sleep(0.2)
print("Would you like to open the OS?")
end
I see a few issues with your code.
First of all, True and False are both meaningless names - which, unless you have assigned something to them earlier, are both equal to nil. Therefore, your Yes and No variables are both set to nil as well. This isn't because true and false don't exist in lua - they're just in lowercase: true and false. Creating Yes and No variables is redundant and hard to read - just use true and false directly.
Second of all, if you're using standard lua downloaded from their website, sleep is not a valid function (although it is in the Roblox version of Lua, or so I've heard). Like uppercase True and False, sleep is nil by default, so calling it won't work. Depending on what you're running this on, you'll want to use either os.execute("sleep " .. number_of_seconds) if you're on a mac, or os.execute("timeout /t " .. number_of_seconds) if you're on a PC. You might want to wrap these up into a function
function my_sleep_mac(number_of_seconds)
os.execute("sleep " .. number_of_seconds)
end
function my_sleep_PC(number_of_seconds)
os.execute("timeout /t " .. number_of_seconds)
end
As for the specific error you're experiencing, I think it's due to your end statement as the end of your program. end in lua doesn't do exactly what you think it does - it doesn't specify the end of the program. Lua can figure out where the program ends just by looking to see if there's any text left in the file. What it can't figure out without you saying it is where various sub-blocks of code end, IE the branches of if statements, functions, etc. For example, suppose you write the code
print("checking x...")
if x == 2 then
print("x is 2")
print("Isn't it awesome that x is 2?")
print("x was checked")
lua has no way of knowing whether or not that last statement, printing the x was checked, is supposed to only happen if x is 2 or always. Consequently, you need to explicitly say when various sections of code end, for which you use end. For a file, though, it's unnecessary and actually causes an error. Here's the if statement with an end introduced
print("checking x...")
if x == 2 then
print("x is 2")
print("isn't it awesome that x is 2?")
end
print("x was checked")
although lua doesn't care, it's a very good idea to indent these sections of code so that you can tell at a glance where it starts and ends:
print("checking x...")
if x == 2 then
print("x is 2")
print("isn't it awesome that x is 2?")
end
print("x was checked")
with regards to your "pastebin" problem, you're going to have to be more specific.
You can implement sleep in OS-independent (but CPU-intensive) way:
local function sleep(seconds)
local t0 = os.clock()
repeat
until os.clock() - t0 >= seconds
end
I would like to evaluate a math string in my corona app. Right now I'm focusing on the trig functions, so let's let the example be the most difficult we're likely to face:
local expr = "2sin(4pi+2)+7"
My goal is for this to somehow be (either) evaluated as is with maybe a pi --> math.pi switch, or to even break it up. The breaking up would be much more difficult, however, since it COULD be as complicated a above, but could also just be sin(1).
So I would prefer to stay as close to the python eval(expr) function as possible, but if that can't happen, I am flexible.
The simplest way would be to replace sin with math.sin (pi with math.pi and so on), add missing multiplications signs, and run it through loadstring, but loadstring is not available in Corona environment.
This means you will need to write your own parser for these expressions. I found a discussion on Corona forums that may help you as a starting point: here, with some details and a demo here
This should do the trick, it is able to use the lua math functions without putting 'math.function' so just sqrt(100) works fine. I threw this together because I have seen this question asked way too many times. Hopes this helps :)
If you have any questions feel free to contact me at rayaman99#gmail.com
function evaluate(cmd,v) -- this uses recursion to solve math equations
--[[ We break it into pieces and solve tiny pieces at a time then put them back together
Example of whats going on
Lets say we have "5+5+5+5+5"
First we get this:
5+5+5+5 + 5
5+5+5 + 5
5+5 + 5
5 + 5
Take all the single 5's and do their opperation which is addition in this case and get 25 as our answer
if you want to visually see this with a custom expression, uncomment the code below that says '--print(l,o,r)'
]]
v=v or 0
local count=0
local function helper(o,v,r)-- a local helper function to speed things up and keep the code smaller
if type(v)=="string" then
if v:find("%D") then
v=tonumber(math[v]) or tonumber(_G[v]) -- This section allows global variables and variables from math to be used feel free to add your own enviroments
end
end
if type(r)=="string" then
if r:find("%D") then
r=tonumber(math[r]) or tonumber(_G[r]) -- A mirror from above but this affects the other side of the equation
-- Think about it as '5+a' and 'a+5' This mirror allows me to tackle both sides of the expression
end
end
local r=tonumber(r) or 0
if o=="+" then -- where we handle different math opperators
return r+v
elseif o=="-" then
return r-v
elseif o=="/" then
return r/v
elseif o=="*" then
return r*v
elseif o=="^" then
return r^v
end
end
for i,v in pairs(math) do
cmd=cmd:gsub(i.."(%b())",function(a)
a=a:sub(2,-2)
if a:sub(1,1)=="-" then
a="0"..a
end
return v(evaluate(a))
end)
end
cmd=cmd:gsub("%b()",function(a)
return evaluate(a:sub(2,-2))
end)
for l,o,r in cmd:gmatch("(.*)([%+%^%-%*/])(.*)") do -- iteration this breaks the expression into managable parts, when adding pieces into
--print(":",l,o,r) -- uncomment this to see how it does its thing
count=count+1 -- keep track for certain conditions
if l:find("[%+%^%-%*/]") then -- if I find that the lefthand side of the expression contains lets keep breaking it apart
v=helper(o,r,evaluate(l,v))-- evaluate again and do the helper function
else
if count==1 then
v=helper(o,r,l) -- Case where an expression contains one mathematical opperator
end
end
end
if count==0 then return (tonumber(cmd) or tonumber(math[cmd]) or tonumber(_G[cmd])) end
-- you can add your own enviroments as well... I use math and _G
return v
end
a=5
print(evaluate("2+2+2*2")) -- This still has work when it comes to pemdas; however, the use parentheses can order things!
print(evaluate("2+2+(2*2)"))-- <-- As seen here
print(evaluate("sqrt(100)"))
print(evaluate("sqrt(100)+abs(-100)"))
print(evaluate("sqrt(100+44)"))
print(evaluate("sqrt(100+44)/2"))
print(evaluate("5^2"))
print(evaluate("a")) -- that we stored above
print(evaluate("pi")) -- math.pi
print(evaluate("pi*2")) -- math.pi