This is a read-only snapshot of the ComputerCraft forums, taken in April 2020.
jmuirhead's profile picture

Getting "keycreator:21: attempt to perform arithetic on local 'iLevel' (a nil value)" and cannot understand/figure out why

Started by jmuirhead, 08 April 2020 - 11:33 PM
jmuirhead #1
Posted 09 April 2020 - 01:33 AM

local sPrefix = "Class "			 
local sSufix = " Keycard"			
local iLevelLength = 6			   
local sDiskSide = "right"			

local tVarargs = {...}
local iLevel = tVarargs[1]
local sLevel = "4"
if (iLevel == "1") then sLevel = "E" end
if (iLevel == "2") then sLevel = "D" end
if (iLevel == "3") then sLevel = "C" end
if (iLevel == "4") then sLevel = "B" end
if (iLevel == "5") then sLevel = "A" end
local hMKey = fs.open("masterkey.lua", "r")
local hKey = fs.open("disk/key", "w")
local sMKey = hMKey.readAll()
local sWriteKey = string.sub(sMKey, 1, iLevel*iLevelLength)
disk.setLabel(sDiskSide, sPrefix .. sLevel .. sSufix)
hKey.write(sWriteKey)
hMKey.close()
hKey.close()
magiczocker #2
Posted 09 April 2020 - 08:51 AM
Did you started your program with some arguments?
If not, the value 'iLevel' is nil, because tVarargs get its values through the {…}.
The {…} means, that all arguments, which you gave your program through starting it with
keycreator arg1 arg2 ...
will be stored in the value 'tVarargs' as a table.

You can make the arguments optional, by changing the
iLevel = tVarargs[1]
to
iLevel = tVarargs[1] or "1"
The "1" represents your fallback-option, if no arguments where specified.
Edited on 09 April 2020 - 07:01 AM