I am sorry if this Question is Off-Topic in any way, I am just starting this book and it's already showing unfamiliar code I've never seen, and I'm a bit curious about it, the book explains the basic, advancements, and advantages of Lua 5.2
, but, again, it is showing pieces of code I am not familiar with, and never seen before, for example, in the book for the first code example, it says io.read
reads a number;
function fact(n) if n == 0 then return 1 else return n = fact(n-1) end end print("enter a number!") a = io.read("*n") -- reads a number print(fact(a))
It also shows a dofile
method, and it explains;
Another way to run chunks is with the 'dofile' function, which immediately executes a file. For instance, suppose you have a file 'lib1.lua' with the following code:
function norm(x,y) return (x^2 + y^2)^0.5 end function twice(x) return 2*x end
Then, in interactive mode, you can type
dofile("lib1.lua") -- load your library n = norm(3.4,1.0) print(twice(n)) -- 7.088018058667
But, non of this code is used in the ROBLOX Lua coding, so I am really puzzled because I've never seen it used before, and it confuses me with the 'lib.lua' file library.
io
is a standard library available in Lua, but which Roblox has removed (because you don't need it). When Lua runs on its own, it needs some way to interact with the rest of the computer and with the user. io
provides that functionality. It allows you to write things to the console, io.write
and also to read user input from the console with io.read
.
In particular, io.read()
will return the first available line of user input. So, for instance, you could make a program like this:
io.write( "What's your name? \n") -- the \n means "new line" name = io.read() io.write( "Hello, " .. name .. "!" )
When a user runs this program with the Lua interpreter, it will say:
What's your name?
They enter a line of text (for instance, if I typed TaslemGuy), and press enter, and it will say:
Hello, Taslemguy!
On the other hand, dofile
is for splitting a script into multiple files. Since complex scripts can become long, it can be helpful to split them into several scripts. When the Lua interpreter is used on its own, individual scripts are individual files.
dofile
tells the interpreter to run a different file. So, for instance, I could have two files:
The first file is called hypo.lua
and it has a function to calculate a hypotenuse.
function calculateHypotenuse( a, b ) print( math.sqrt( a^2 + b^2 ) ) end
The second is the program I'll be testing, called test.lua
x = 4 y = 3 calculateHypotenuse(x, y)
I run this file, test.lua
. However, there's an error, because it I never defined calculateHypotenuse
inside of it. So I ask it to include the first file, by instead writing:
x = 4 y = 3 dofile("hypo.lua") calculateHypotenuse(x, y)
If you want to be able to use these, you'll need to install Lua and use it from a command line.