Base globals

The base globals are functions implemented by Lua that are always available globally.

Global functions

Functionassert
Takes in a boolean value where, on the condition that it evaluates to false or nil an error is thrown with the specified message.
Syntax assert(
  • expression : boolean
  • message : string
)
Returns nil
Part of CC:Tweaked
API Base globals
ExampleAsserting an error
Throws an error with specified error message due to the condition being false.
Code
assert(false, "example error message")
Output
program.lua:1: example error message
ExampleError checking in a function
Throws an error when something other than an even number is given
Code
function assertNumber(number)
  assert(number/2 == math.ceil(number/2), "this is odd")
end
assertNumber(4) --Passes by this since it is an even number
assertNumber('foo')
Output
program.lua:5: this is odd
Functiondofile
Loads and then runs a file, using loadfile. The following is what the internals of this function look like:
function dofile(fileName)
  local f = assert(loadfile(fileName))
  return f()
end
Syntax dofile(
  • filename : string
)
Returns whatever the file returns
Part of CC:Tweaked (source)
API Base globals
See also loadfile
ExampleRequire a file from the directory that the currently running program is in
Code
<nowiki>
local myFileData = dofile("someFile")
</nowiki>
Output Nothing, unless there is an error in someFile
Functionerror
Throws an error with the specified message at the current line and call frame or if specified, level frames upward.
Syntax error(
  • message : string
  • level? : number
)
Returns nil
Part of CC:Tweaked
API Base globals
ExampleThrowing an error
Throws an error with specified error message.
Code
error("example error message")
Output
program.lua:1: example error message
ExampleThrowing an error at a different level
Throws an error with specified error message at a higher frame.
(note how it specified the error as happening on line 5, where myFunction() is being called, because we traversed up.)
Code
local function myFunction()
  error("example error message", 2)
end

myFunction()
Output
program.lua:5: example error message
Functiongetmetatable
Returns the metatable of a table - this is whatever has been set with setmetatable. Some keys in this metatable will (if they exist) be called when certain operators are used - see the Lua Users wiki. However if the metatable contains the __metatable key the value of it will be returned instead. If there is no metatable nil is returned.
Syntax getmetatable(
  • table : table
)
Returns table
Part of CC:Tweaked
API Base globals

Ipairs

Functionload
Loads chunk ld (or, if ld is a function, loads the chunk returned by it) as a function and returns it. Error messages use source if available, or a representation of ld.
Syntax load(
  • ld : various
  • source? : string
)
Returns function or nil
Part of CC:Tweaked
API Base globals
ExampleLoading a string
Prints "Hello World" from a loaded function
Code
load("print('Hello World')")()
Output Hello World
Functionloadfile
Takes a filename and will return a function if it's succesful. If it's not, it will return nil and a error message.  Note: The format is loadfile( filename, env ) is also accepted, for older versions, but shouldn't be used.
Syntax loadfile(
  • filename : string
  • mode : string
  • env : table
)
Returns function string
Part of CC:Tweaked (source)
API Base globals
ExampleLoading files and printing error.
Code
function executeFile( filename, ... )
  local ok, err = loadfile( filename )
  print( "Running "..filename )
  if ok then
    return ok( ... )
  else
    printError( err )
  end
end

executeFile( "doesnotexist.lua" )
executeFile( "rom/programs/id.lua" )
Output
Running doesnotexist.lua
File not found
Running rom/programs/id.lua
This is computer #1

Loadstring

Functionnext
Gets the next index and its value of the table table starting at index. If index is nil, then it returns an initial index and value. This function returns nil if called with the last index or table is nil. However, the order that indices are returned are not in order, even if table has numerical indices.
Syntax next(
  • table : table
  • index? : various
)
Returns various index, various value
Part of CC:Tweaked
API Base globals
ExampleCheck if a table is empty
Errors if table is empty, or prints the table's contents.
Code
local t1 = {}
if next(t1) then
  print(textutils.serialize(t1))
else
  error("empty table", 2)
end
Output
program.lua:4:empty table

Package Pairs

Functionpcall
Calls func (with arguments as parameters) in protected modeThat is, any errors thrown while the function is executing are caught and returned by the nearest enclosing pcall.
Syntax pcall(
  • func : function
  • arguments... : any
)
Returns bool false, any error | bool true, any returns
Part of Lua (source)
API Base globals
ExampleCatch errors from a named function
Execution of badFunction will throw an error (and abort the program), but running it within pcall allows the programmer to make a decision about the error
Code
<nowiki>
local function codeSnip()
  error("Some error message")
end

local ok, err = pcall(codeSnip)
if not ok then
  print("Execution of badFunction errored with " .. err)
else
  print("Function returned normally the value " .. err)
end
    </nowiki>
Output
<nowiki>
Execution of badFunction errored with Some error message
</nowiki>
Functionprint
Prints any number of arguments (space separated) at the current cursor position in the current term. All the arguments will automatically be converted to a string using the tostring function, and concatenated, separated by spaces. This function automatically moves to the next line after writing. As well as this, it performs text wrapping, meaning if the string is too big for the term, it will continue writing on the next line. print returns the number of lines it printed.
Syntax print(
  • toPrint... : any
)
Returns number linesPrinted
Part of CC:Tweaked (source)
API BIOS globals
ExamplePrint a basic string
Prints "Hello, world!" to the current term.
Code
<nowiki>
print("Hello, world!")
    </nowiki>
Output
Hello, world!
ExamplePrint multiple strings
Prints "foo bar" to the current term.
Code
<nowiki>
print("foo", "bar")
    </nowiki>
Output
foo bar
ExamplePrint multiple types
Prints strings and numbers to the current term in a single print call.
Code
<nowiki>
local cats = 5
local dogs = 3
print("Cats:", cats, "Dogs:", dogs)
    </nowiki>
Output
Cats: 5 Dogs: 3

Rawequal Rawget Rawset Select Setmetatable

Functiontonumber
Parses a number contained in a string. Useful for retrieving numeric values from user input. If str cannot be parsed as a number, the function will return nil.
Syntax tonumber(
  • str : string
)
Returns number | nil
Part of Lua (source)
API Base globals
ExampleAdd 5 to a number entered by the user
Prompt the user for a number, then increment it by 5 and print the result.
Code
<nowiki>
local num = tonumber(read())
if num == nil then
    printError("Please enter a number!")
else
    print(num + 5)
end
    </nowiki>
Output If the user did not enter a valid number, the program will print "Please enter a number!". If the user did enter a valid number, it will print its value + 5.
Functiontostring
Converts x to a string.

 Note: If used on a table, this function will return table: address where address is the memory address of the table. To turn the actual table contents into a string, use textutils.serialise.

 Note: You can also use x.."".
Syntax tostring(
  • x : any The value to convert to a string.
)
Returns string
Part of Lua (source)
API Base globals
ExampleConvert a number to a string.
Takes the number 64, converts it to a string and then prints it.
Code
<nowiki>
local stringFromNumber = tostring(64)
print(stringFromNumber)
    </nowiki>
Output
64
Functiontype
Returns a string representing the type of the given variable.
Syntax type(
  • variable : any
)
Returns string type
Part of CC:Tweaked
API Base globals
ExamplePrint various types
Prints the types of several variables
Code
local tbl = {}
local str = ""
local func = function() end
local thread = coroutine.create( function() end )
local bool = true
local number = 1
local nothing = nil
print(type(tbl))
print(type(str))
print(type(func))
print(type(thread))
print(type(bool))
print(type(number))
print(type(nothing))
Output
table
string
function
thread
boolean
number
nil
ExampleValidate an argument
Throws an error if the function is not called with the correct arguments
Code
local function foo(bar)
  if type(bar) ~= "number" then
    error("bad argument #1 (expected number, got " .. type(bar) .. ")", 2)
  end
end
foo(1)
foo("Hello World")
Output program.lua:7: bad argument #1 (expected number, got string)

Xpcall

gollark: It was a perfect metaphorical storm of opposing ideologies.
gollark: … no?
gollark: There are many other issues but that's one of them.
gollark: I'm probably going to university in about two years. The ones here cost much, much less. Thus no.
gollark: Or all the random countries with dictatorships and whatnot, but sure.
This article is issued from Computercraft. The text is licensed under Creative Commons - Attribution - Sharealike. Additional terms may apply for the media files.