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

Define a functions param

Started by dCode, 17 July 2017 - 12:53 AM
dCode #1
Posted 17 July 2017 - 02:53 AM
How will I define a functions parameter like we do in JavaScript, php, cSharp, etc

For example in javascript:

function name (param1, param2 = true) {
  // Do something
}

But whenever I try to do something similar in Lua it crashes with:

bios.lua:14: [string "require.lua"]:1: ')' expected

What I did was:


function require (mod, useExtension = true)

What am I doing wrong?
Bomb Bloke #2
Posted 17 July 2017 - 06:55 AM
http://www.lua.org/pil/5.3.html
Edited on 17 July 2017 - 04:59 AM
Lupus590 #3
Posted 17 July 2017 - 11:07 AM
Lua has no concept of default values in it's arguments. Instead Lua developers do this.


function example ( optionalArg ) --# prints given string or "I am an example" if no string is given

	if optionalArg == nil then
		--# assign default value to optionalArg
		optionalArg = "I am an example."
	end

	--# if you want to be fancy then you can replace
	--# the above if block with the following
	optionalArg = optionalArg or "I am an example."

	--# repeat one of the above for each argument you need to check


	--# normal function stuff here
	print(tostring(optionalArg))
end
Edited on 17 July 2017 - 09:09 AM