fix error attempt to perform arithmetic (add) on string - lua

if (hit.Name == "Base") then return end
hit:BreakJoints()
if (hit.Anchored == true) then hit.Anchored = false end
wait(.5)
for i=1, 10 do
hit.Transparency = hit.Transparency + 0.1
wait(0.2)
end
print("removing" + hit:GetFullName()) <---- here
hit:remove()
end
connection = script.Parent.Touched:connect(onTouched)
but i got " attempt to perform arithmetic (add) on string error "in line 10 can you fix this error pls?

if hit:GetFullName() is returning a string, in Lua, we use two dots .. to concatenate two strings instead of the plus +:
print("removing " .. hit:GetFullName())

Related

Lua-Logging data from Device to a file-Excel- Lua scripts

I have the following Lua script that collects temperature values from a device and I would like to log the output data below to an excel spreadsheet. Any help would be greatly appreciated.
if globalsFile == nil then
dofile("globals.lua")
end
if utilFile == nil then
dofile("util.lua")
end
heaterDuration = 0
heaterInterval = 2
heaterTimeout = 20
index = 1
heater.ON()
print("The heaters have been turned on")
print("Temperatures will be updated below every " .. heaterInterval .. " seconds")
print("Item,Time Point,Top,Bottom,Ambient")
tempIncrease = 'n'
while (heaterDuration < heaterTimeout) do
topTemp = heater.top()
bottomTemp = heater.bottom()
ambientTemp = temperature.ambient()
print(index .. "," .. heaterDuration .. "," .. topTemp .. "," .. bottomTemp .. "," .. ambientTemp)
heaterDuration = heaterDuration + heaterInterval
os.sleep(heaterInterval * 1000)
end
Output
Item,Time Point,Top,Bottom,Ambient
1,0,37.022136688232,37.202819824219,28.257425308228
1,2,37.022136688232,37.202819824219,28.282178878784
1,4,37.022136688232,37.202819824219,28.282178878784
1,6,37.022136688232,37.202819824219,28.282178878784
1,8,37.022136688232,37.202819824219,28.282178878784
1,10,37.022136688232,37.202819824219,28.282178878784
1,12,37.022136688232,37.202819824219,28.282178878784
1,14,37.022724151611,37.202819824219,28.282178878784
1,16,37.022136688232,37.202819824219,28.282178878784
1,18,37.022136688232,37.202819824219,28.282178878784```
If you replace the while loop with something like this, depending on the environment that your Lua runs in, you should be creating a CSV file, which is a readable plain text file with literally just values (or strings, but then it can get more complicated) values separated by commas, or tabs, but let's stick to commas here.
The biggest differences are the creation of the mycsv file object, switchin the print to mycsv:write() (while making sure there is a newline), and then closing (and maybe flushing unwritten data) the file object at the end.
mycsv = io.open("mydata.csv", "w")
mycsv:write("Item,Time Point,Top,Bottom,Ambient\n")
while (heaterDuration < heaterTimeout) do
topTemp = heater.top()
bottomTemp = heater.bottom()
ambientTemp = temperature.ambient()
mycsv:write(index .. "," .. heaterDuration .. "," .. topTemp .. "," ..
bottomTemp .. "," .. ambientTemp .. "\n")
heaterDuration = heaterDuration + heaterInterval
os.sleep(heaterInterval * 1000)
end
mycsv:close()
See also: https://luabyexample.org/docs/files/

Why is this string not splitting in lua

So I am working on a project and I need to split a string that would look something like this:
if (x == 2){ output("Hello") }
This is my code:
local function splitIfStatement(str)
local t = {}
t[1] = ""
t[2] = ""
t[3] = ""
local firstSplit = false
local secondSplit = false
local thirdSplit = false
str:gsub(".", function(c)
if c == "(" then
firstSplit = true
end
if firstSplit == true then
if c == "=" then
firstSplit = false
secondSplit = true
else
if c == "(" then
else
t[1] = t[1] .. c
end
end
end
if secondSplit == true then
if c == ")" then
secondSplit = false
thirdSplit = true
else
if c == "=" then
else
t[2] = t[2] .. c
end
end
end
end)
return t
end
I need to split the string at "(" so t[1] is only equal to "x" and t[2] is equal to 2 and then t[3] is equal to the "output()"
But when I run my code(note I haven't added the t[3]) t[1] returns: "x "Hello") }" and t[2] returns 2 like it should.
Anyways why isn't the split function working on the first split but it works on the second.
Thanks!
In your loop you set firstSplit true if it hits a ( this happens in 2 places in your example, before x and right before "Hello"
you can fix this by setting firstSplit true and ignore the leading if ( before you beginning the loop. Then you allow the logic you have to handle the rest.
I also notice you dont have any logic that references t[3] right now.
That all said you really should use a pattern to parse something like this.
local function splitIfStatement(str)
t = {str:match("if%s*%((%w+)%s*[=<>]+%s*(%d+)%)%s*{(.+)}")}
return t
end
this pattern is very narrow and expects a specific type of if statement, you can learn more about lua patterns here: Understanding Lua Patterns
If the input is of the form
if (AAA == BBB){ CCC("Hello") }
with possible whitespace around the fields in question, then this code works:
S=[[if (x == 2){ output("Hello") } ]]
a,b,c = S:match('%(%s*(.-)%s.-%s+(.-)%)%s*{%s*(.-)%(')
print(a,b,c)

How can I get only the decimal from a float in lua?

How would I be able to do the following?
local d = getdecimal(4.2) --> .2
Assuming you're only working with numbers greater than 0, modulus is the best way to go:
print(4.2%1)
Otherwise the fmod function in the math library should do the trick.
print(math.fmod(4.2,1))
You can take a little bit of a non-paradigmatic approach to this by taking the number and turning it into a string:
function getDec(num)
return tostring(num):match("%.(%d+)")
end
print(getDec(-3.2))
--2
function getDecimal(inp)
local x = tostring(inp)
local found_decimal = false
local output_stream = ""
for i = 1, string.len(x) do
if found_decimal == false then
if string.sub(x, i+1, i+1) == "." then
found_decimal = true
end
else
output_stream = output_stream .. string.sub(x,i, i)
end
end
return output_stream
end
What that does is it basically returns everything after the decimal it found as a string.
And if you want to turn the return back into a number do this:
return tonumber("0" .. output_stream)

Syntax error: player.lua:11: '=' expected near '<eof>'

I have recently been learning Lua with Love2d, so I decided to start making a simple RPG. It's quite simple. The console is where you play, and the extra window is where you can see your stats, equip items, ect.
But, I have run into a problem! Whenever I run the code, I see this main.lua:15: '=' expected near 'else'
I will include the code (all 3 files) below.
This is main.lua
function love.load()
love.graphics.setBackgroundColor( 255, 255, 255 )
require("player")
print("Enter your name")
pcStats.Name = io.read()
print("What class are you, " .. pcStats.Name .. "?")
pcStats.Class = io.read()
if pcStats.Class == "Ranger" then
os.execute("cls")
pcInv.InvSpace = 10
pcInv.Items.basicBow = Basic Bow
else
print("Error: Invalid Class. Please restart game")
end
print("What would you like to do? CODE END")
input = io.read()
end
function love.draw()
love.graphics.setColor( 0, 0, 0 )
love.graphics.print( "Level: " .. pcStats.Level, 1, 1 )
love.graphics.print( "Inv Space: " .. pcInv.InvSpace, 1, 20 )
love.graphics.print( "Inv: " .. pcInv.Items, 1, 40 )
end
Here is player.lua This is where the game variables are stored
pcStats = {}
pcStats.Level = 1
pcStats.XP = nil
pcStats.Name = nil
pcStats.Class = nil
pcStats.Atk = nil
pcStats.Def = nil
pcInv = {}
pcInv.InvSpace = nil
pcInv.Items.testsword = testing sword
And last but not least, here is the conf.lua used for love2d
function love.conf(t)
t.modules.joystick = true
t.modules.audio = true
t.modules.keyboard = true
t.modules.event = true
t.modules.image = true
t.modules.graphics = true
t.modules.timer = true
t.modules.mouse = true
t.modules.sound = true
t.modules.thread = true
t.modules.physics = true
t.console = true
t.title = "Lua RPG Alpha v0.0.1"
t.author = "Zach Herzer"
end
Line 15 is this:
pcInv.Items.basicBow = Basic Bow
Basic Bow isn't valid Lua code. I am pretty sure you meant something else - perhaps a string?
pcInv.Items.basicBow = "Basic Bow"
While we're at it,
pcInv.Items.testsword = testing sword
has a similar problem.

lua - calling a function from a string

From what I've read on this site the below should work.
Can some kindly soul please point out where I'm going wrong?
I've embedded more description and print returns in the code hopefully to make easier reading
local m = {
{opt = "Solar Panels", cmd = "solarPanel"}
-- There are many more options here.
}
function doTheMenu()
print("Welcome to Spyder's Factory")
print("")
print("What would you like to make?")
local n = 1
local l = #m - 1
while true do --This while loop may or may not be relevant to the question, it's the menu
term.clear() --this is ComputerCraft lua, the term function is defined
term.setCursorPos(1,2) --elsewhere in an API
for i, j in pairs(m) do
if i == n then
if i < 10 then print(i, " ["..j.opt.."]") else print(i, " ["..j.opt.."]") end
fsel = j.cmd --set fsel to the function name I require in case of a break
tsel = j.opt --Ditto, tsel, human-friendly name
else
if i < 10 then print(i, " "..j.opt) else print(i, " "..j.opt) end
end
end
local a, b = os.pullEvent("key")
if b == 200 and n > 1 then n = n - 1 end
if b == 208 and n <= l then n = n + 1 end
if b == 28 then break end
end
write("\nSure, how many "..tsel.."? ")
qty = tonumber(read())
req[fsel] = req[fsel] + qty
str = fsel.."("..qty..")"
print("Loading function '"..fsel.."("..qty..")'") --Returns "Loading function 'solarPanel(1)'"
func = loadstring(str)
print(func) --Returns "function: 2cdfc5a7"
print("Loading function")
func() --The error line, Returns "string:1: attempt to call nil"
--tellUserWhatNeed()
--makeItHappen()
end
doTheMenu()
The issue is the code fails to run with the error:
string:1 attempt to call nil
Also what is term variable, if that's all your code, term is not defined and is null)
That said: either _G[fsel] is nil or fsel is nil ?
Are you sure you have function declared in _G with the name stored in fsel?
e.i. call before the problem line print (_G[fsel]) to see what it gives you.
This was the solution that ended up working:
local f = loadstring(str)
if f then
setfenv(f, getfenv())
f()
end
This replaces the lines above:
print("Loading function '"..fsel.."("..qty..")'")
func = loadstring(str)
print(func)
print("Loading function")
func()
As well as adding basic error handling for loading the function

Resources