Loading presentation...

Present Remotely

Send the link below via email or IM

Copy

Present to your audience

Start remote presentation

  • Invited audience members will follow you as you navigate and present
  • People invited to a presentation do not need a Prezi account
  • This link expires 10 minutes after you close the presentation
  • A maximum of 30 users can follow your presentation
  • Learn more about this feature in our knowledge base article

Do you really want to delete this prezi?

Neither you, nor the coeditors you shared it with will be able to recover it again.

DeleteCancel

Full Lua Tutorial Talk

Presentation used during a 1-day Lua Tutorial at the Game Developer's Conference, San Francisco, March 2010.
by

Steve Collins

on 18 December 2017

Comments (0)

Please log in to add your comment.

Report abuse

Transcript of Full Lua Tutorial Talk

Who am I?
C64 game developer
Co-founder / CTO
Co-founder / CTO
< 90
98 - 06
08 - now
96 - now
Senior Lecturer
Software engineering, real-time rendering
TCD
Real-time physics engines
Game scripting languages & VMs
http://gmarceau.qc.ca/blog/2009/05/speed-size-and-dependability-of.html
sweeping
marking
headroom
startup
settling
steadystate
Why Lua?
Small
Fast
Embeddable (easy bindings)
Portable
Helpful and active community
PS3 / Xbox360: 300kb+
No lexer / parser
ANSI (ISO) C
Official Site
Lua Users Wiki
Lua-l mailing list
Fastest interpreted dynamic language
Why scripting (for console games)?
Iteration
Rapid prototyping
Fast interpreter
DLC
Sandbox
Modding
Can't write executable code on PS3, Xbox360, iPhone, ...
Reduce need for expensive title updates
Game modes
New levels
Additional props + behaviors
New UI
Code = data
Hot Load = no recompile
Edit & continue
VM
Interpreted byte-code
Dynamically typed
Automatic Garbage Collection
Register machine
Thread-safe (not multi-threaded)
GC'ed objects passed by reference
Lexical scoping
Incremental
Mark & Sweep
Compilation
Single pass (lexer - parser - bytecode generator)
Hand-rolled (no lex/yacc etc.)
Operates on "chunks"
a unit of execution
collection of statements
anonymous function
anonymous
functions
pcall()
ChunkSpy
http://luaforge.net/projects/chunkspy/
Bytecode Format
Sort
Insertion / removal
Concatenation
Create
Yield / resume / wrap
Status check
Trig functions
Random
log, sqrt, pow, exp, floor ...
ANSI C rand()

Basic Types
nil
boolean
number
string
userdata
lightuserdata
function
thread
table
Lua is "weakly typed"
Variables don't have types
Values do have types
false, nil
everything else
(incl. "", zero)
false
true
double
8-bit clean array of chars (can contain '\0')
Immutable (hashed on creation, GCed)
void*
Garbage Collected
Associative arrays
Array part
Hash part
power of 2 table size
internal chaining
Brent's variation
any Lua object can be a key
Metatables and Metamethods
Special table, attached to Table or Userdata
Defines "Events" = behavior over-rides
Metatables and Metamethods
__index
__newindex
called when tag doesn't exist
called when new tag added
Simple O.O.
Fallback table
(base-class?)
Simple O.O.
Simple O.O. (take #2)
Factory
Simple O.O. (take #3)
Simple O.O. (take #3 cntd.)
Programming in Lua
Lua Programming Gems
Roberto Ierusalimschy
Roberto Ierusalimschy, Ed.
PiL
Online Sources
1
2
3
functions are first class objects
access tables like records / objects / arrays
Control Structures
While
For
If
numeric
increment
generic
generic (with partial list use)
table iterator
unused result
returns type of argument
Globals vs. Locals
Sandboxing
set different global tables
(with different global 'a')
for each function
All functions are global entries in current environment table
=> can control which functions are accessible, script-by-script
Sandboxing
Happens all the time...
We can "lock" the global table:
clear entry "len" from _G
Backdoor
co-operatively scheduled light-weight threads (semi-coroutines)
Own stack
Doesn't use C Stack
Doesn't use hardware thread / context switch
coroutine library:
create()
resume()
yield()
also wrap(), status()
Closures
locals of enclosing functions are available to the enclosed function
anonymous functions
lambdas
functions in Lua are "first class" values
anonymous
generator
Upvalues
"lexical scoping"
2 copies of count
"private" variables
each function generated
has its own unique "count"
More Sandboxing!
varargs
Global
Non-global
__metatable
__gc
Serialisation
raw
metamethod
For full state serialization use Pluto
http://luaforge.net/projects/pluto/
Incremental Mark & Sweep
mark all "white"
trace from "roots"
mark reachable set "black"
sweep heap and
delete "white"
"grey" required for incremental
(potentially reachable)
Controlling GC
From Script:
Automatic:
pause = "wait" between triggering GC cycles
step multiplier = speed of GC relative to allocations
just "happens"!
Pause
100 - start immediately
110 - start when mem grows by 10%
200 - start when mem doubles
Multiplier
0 - collect everything (STW)
50 - collect 50% of allocs since last GC
200 - collect at double rate of allocs
magic param
GC
Incremental Mark & Sweep
More on this later...
Typical Memory Profile with GC
Memory Management
All allocations passed to a user provided allocator
userdata
glob of data managed by Lua GC
"opaque" to Lua
can have a metatable
Perfect for reflecting game objects
lightuserdata
32-bit void*, not garbage collected
"opaque" to Lua
no metatable
Used for storing pointers to game resources
VM Managed
Game Managed
Strategies
automatic
fixed work
fixed time
dump cycles
other thread
Lua in Game Production
Regex
Formatting
Manipulation
Introspection
Hook functions
Traceback
Debugging: Introspection
Get info on functions, locals, upvalues, coroutines:
source file and line, type information, name, etc.
stack level
Debugging: Hooks
(call, return, line, count)
Checked at each iteration of interpreter
Good idea to compile out for final deployment (~5%)
Enable all hooks, count = 3
yield() on a
count hook
coroutine timeslicing
Binding to Game Engine
Lua API Stack
Stack used to thunk data
between application runtime
and the Lua VM
Calling Lua from C:
Calling C from Lua:
Need to register C/C++ "callbacks" with Lua VM.
Callback must pop params from stack and coerce
Push result on stack (if any)

Many libraries exist to simplify this:
LuaPlus, SWIG, LuaBind, ToLua++
Each C-function has it's own stack
Calling C from Lua:
Absolute
Relative
callback
Lua:
register
Proper tail-recursion
Registry
Packages / Modules
Regex
Error Handling & Exceptions
Bytecode stripping
AUX Library
Weak Tables
Finalizers
Thanks
steve@kore.net
www.kore.net

Full transcript