Base globals

From ComputerCraft
Jump to: navigation, search

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

Global functions

FunctionFunctionassert
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()
Returns nil
Part of CC:Tweaked
API Base globals
ExampleExampleAsserting 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
ExampleExampleError 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

Dofile

FunctionFunctionerror
Throws an error with the specified message at the current line and call frame or if specified, level frames upward.
Syntax error()
Returns nil
Part of CC:Tweaked
API Base globals
ExampleExampleThrowing an error
Throws an error with specified error message.
Code
error("example error message")
Output
program.lua:1: example error message
ExampleExampleThrowing 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
FunctionFunctiongetmetatable
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. More info available in this image.
Syntax getmetatable()
Returns table
Part of CC:Tweaked
API Base globals

Ipairs Load Loadfile Loadstring Next Package Pairs

FunctionFunctionpcall
Calls func (with arguments as parameters) in protected mode—That is, any errors thrown while the function is executing are caught and returned by the nearest enclosing pcall.
Syntax pcall()
Returns bool false, any error | bool true, any returns
Part of Lua (source)
API Base globals
ExampleExampleCatch 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
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
Output
Execution of badFunction errored with Some error message


FunctionFunctionprint
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
ExampleExamplePrint a basic string
Prints "Hello, world!" to the current term.
Code
print("Hello, world!")
Output
Hello, world!
ExampleExamplePrint multiple strings
Prints "foo bar" to the current term.
Code
print("foo", "bar")
Output
foo bar
ExampleExamplePrint multiple types
Prints strings and numbers to the current term in a single print call.
Code
local cats = 5
local dogs = 3
print("Cats:", cats, "Dogs:", dogs)
Output
Cats: 5 Dogs: 3

Rawequal Rawget Rawset Select Setmetatable

FunctionFunctiontonumber
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()
Returns number | nil
Part of Lua (source)
API Base globals
ExampleExampleAdd 5 to a number entered by the user
Prompt the user for a number, then increment it by 5 and print the result.
Code
local num = tonumber(read())
if num == nil then
    printError("Please enter a number!")
else
    print(num + 5)
end
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.


FunctionFunctiontostring
Converts x to a string.

Note 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 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
ExampleExampleConvert a number to a string.
Takes the number 64, converts it to a string and then prints it.
Code
local stringFromNumber = tostring(64)
print(stringFromNumber)
Output
64


FunctionFunctiontype
Returns a string representing the type of the given variable.
Syntax type(
  • variable : any
)
Returns string type
Part of CC:Tweaked
API Base globals
ExampleExamplePrint various types
Prints the types of several variables
Code
local tbl = {}
local str = ""
local func = function() end
local bool = true
local number = 1
local nothing = nil
print(type(tbl))
print(type(str))
print(type(func))
print(type(bool))
print(type(number))
print(type(nothing))
Output
table
string
function
boolean
number
nil
ExampleExampleValidate 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