This first edition was written for Lua 5.0. While still largely relevant for later versions, there are some differences.
The fourth edition targets Lua 5.3 and is available at Amazon and other bookstores.
By buying the book, you also help to support the Lua project.
The fourth edition targets Lua 5.3 and is available at Amazon and other bookstores.
By buying the book, you also help to support the Lua project.
Programming in Lua |
Part I. The LanguageChapter 3. Expressions |
3.6 – Table Constructors
Let us now see the basic structure of Lua program, so that it will be easy for you to understand the basic building blocks of the Lua programming language. A Lua program consists of various tokens and a token is either a keyword, an identifier, a constant, a string literal, or a symbol. Lua for Windows. Powered by GitBook. Tools Cheat Sheet. Whether you're a seasoned server admin or a player wanting something extra (or both.
Constructors are expressions that create andinitialize tables.They are a distinctive feature of Luaand one of its most useful and versatile mechanisms.
The simplest constructor is the empty constructor,
{}
, which creates an empty table;we saw it before.Constructors also initialize arrays(called also sequences or lists).For instance, the statementwill initialize days[1]
with the string 'Sunday'
(the first element has always index 1, not 0),days[2]
with 'Monday'
,and so on:Constructors do not need to use only constant expressions.We can use any kind of expression for the value of each element.For instance, we can build a short sine table as
To initialize a table to be used as a record,Lua offers the following syntax:which is equivalent to
No matter what constructor we use to create a table,we can always add and remove other fields of any type to it:That is, all tables are created equal;constructors only affect their initialization.
Every time Lua evaluates a constructor,it creates and initializes a new table.Consequently, we can use tables to implement linked lists:This code reads lines from the standard inputand stores them in a linked list, in reverse order.Each node in the list is a table with two fields:
value
, with the line contents,and next
, with a reference to the next node.The following code prints the list contents:(Because we implemented our list as a stack,the lines will be printed in reverse order.)Although instructive,we hardly use the above implementation in real Lua programs;lists are better implemented as arrays,as we will see in Chapter 11.We can mix record-style and list-styleinitializations in the same constructor:The above example also illustrates how we can nest constructorsto represent more complex data structures.Each of the elements
polyline[1]
, ..., polyline[4]
is a table representing a record:Those two constructor forms have their limitations.For instance,you cannot initialize fields with negative indices,or with string indices that are not proper identifiers.For such needs, there is another, more general, format.In this format,we explicitly write the index to be initialized as an expression,between square brackets:That syntax is more cumbersome, but more flexible too:Both the list-style and the record-style forms are specialcases of this more general one.The constructoris equivalent toand the constructoris equivalent to
Lua Cheat Sheet
For those that really want their arrays starting at 0,it is not difficult to write the following:Now, the first value,
'Sunday'
, is at index 0.That zero does not affect the other fields,but 'Monday'
naturally goes to index 1,because it is the first list value in the constructor;the other values follow it.Despite this facility,I do not recommend the use of arrays starting at 0 in Lua.Remember that most functions assume thatarrays start at index 1,and therefore will not handle such arrays correctly.You can always put a comma after the last entry.These trailing commas are optional, but are always valid:Such flexibility makes it easier to write programs that generate Lua tables,because they do not need to handle the last element as a special case.
Finally, you can always use a semicolon instead of a comma in a constructor.We usually reserve semicolons to delimitdifferent sections in a constructor,for instance to separate its list part from its record part:
Copyright © 2003–2004 Roberto Ierusalimschy. All rights reserved. |
Essential Objects
ClassDescriptionPartA physical brick in the world.ModelA container for Parts.FolderA container for Scripts and value objects.ScriptA container for Lua source code.LocalScriptA Script that runs its code on a client.Basic math functions
OperationDescriptiona + b
Adds a
and b
.a - b
Subtract a
and b
.a * b
Multiply a
and b
.a / b
Divides a
by b
.a % b
Remainder of a
divided by b
.FunctionDescriptionmath.random(n)
Returns random number from 1
to n
(no negatives).math.random(a, b)
Returns random number from a
to b
.math.max(...)
Returns the largest number.math.min(...)
Returns the smallest number.math.floor(n)
Rounds n
down.math.ceil(n)
Rounds n
up.math.abs(n)
Returns absolute value of n
.math.sqrt(n)
Returns square root of n
.math.pi
Lua Cheat Sheet Pdf
Approx equal to3.14159
It's important to work out problems by hand before translating their solutions into code. Algebra is necessary for success. Read about all math functions here.String functions
OperationDescriptiona .. b
Combine two strings.FunctionDescriptionstring.len(str)
Returns length of str
.string.upper(str)
Returns str
in upper-case.string.lower(str)
Returns str
in lower-case.string.reverse(str)
Returns str
in reverse.string.rep(str, n)
Returns str
repeated n
timesstring.sub(str, a, b)
Return sub-string of str
from a
to b
.A string is a collection of characters, or text. An example of a string property is the Name
property. Read all string manipulation functions here.Tables
Tables are a collection of values. They are defined using curly braces {} with values separated by commas. Access the values inside using square brackets []. Tables are sometimes called arrays. Use a for loop to work with all items in a table individually. The :GetChildren() method returns a table of children in an object.Constants
game
Parent of all game services.workspace
Container for all bricks and models are stored.script
The currently running script.![Roblox lua cheat sheet Roblox lua cheat sheet](/uploads/1/1/4/1/114140215/658260808.jpg)
Finding Objects
Use a period to access an object's children. Use .Parent to access an object's parent. Use constants like game, workspace, and script to identify objects in the hierarchy.Creating objects
How do I create an object?UsingInstance.new(class)
and setting the parent:object.Parent = parent
How do I access an object's properties?Use a period (.
):print(object.Name)
How do I set an object's properties?Use a period (.
) and equals sign (=
):part.Transparency = .5
How do I destroy an object?Using object:Destroy()
How do I copy a preexisting object?Using object:Clone()
and setting the parent:newTree = workspace.Tree:Clone()
newTree.Parent = workspace
General Object Functions
Method nameDescription:FindFirstChild(name)
Return a child with name
or nil
if it doesn't exist.:WaitForChild(name)
Pauses until a child with a name exists and returns it.:IsA(className)
Return whether the object is a certain type of object.Roblox Lua Cheat Sheet
:Clone()
Makes and returns a copy of an object.:Destroy()
Permanently delete an object.:GetChildren()
Return a list of an object's children.These are functions (aka methods) for all classes of ROBLOX objects. Read about all methods here.Event basics
Events are specific occurrences relating to objects. When an event fires, or occurs, all connected functions are called.Basic functions
wait(n)
Wait n
seconds then continue.print(...)
Display something in the Output window.Variables
Variables store data of any kind - numbers, strings, tables, objects or nil (nothing). A local variable is only accessible in the block of code it is defined in.If statements
If statements will run their code if the value between if/then is true (or not nil). They can one an else block, or any number ofLua Api Cheat Sheet
elseif blocks.Loops
Numeric for loopFor counting numerically.Example: Count from
1
to 5
:for i = 1, 5 do
print(i)
end
Generic for loopMost often used for object children.Example: Print all children in object:
for i, child in pairs(object:GetChildren()) do
print(child.Name)
end
While loopPerform code until a condition is false.Example: Remove all children named 'Ball'
while object:FindFirstChild('Ball') do
object.Ball:Destroy()
end
Repeat-until loopPerform code once, then again until a condition is true.Ex.:
Lua Cheat Sheet
Copy objects until there are 5.repeat
newObject = object:Clone()
newObject.Parent = workspace
wait(1)
until #workspace:GetChildren() >= 5
Loops are used to iterate, or repeat code a number of times.