References: 1. “Programming in LUA, 2 nd ed.”, Roberto Lerusalmschy Chapters 1-6 2. “Lua...

22
LUA INTRO References: 1. “Programming in LUA, 2 nd ed.”, Roberto Lerusalmschy Chapters 1-6 2. “Lua Reference Manual” (included in Lua installation or online)

Transcript of References: 1. “Programming in LUA, 2 nd ed.”, Roberto Lerusalmschy Chapters 1-6 2. “Lua...

LUA INTRO

References:

1. “Programming in LUA, 2nd ed.”, Roberto Lerusalmschy Chapters 1-6

2. “Lua Reference Manual” (included in Lua installation or online)

What is Lua? A very lightweight scripting language

Very bare-bonesEasy C integration (note: NOT C++)Reasonably Fast (for a scripting language)

Used as a scripting language in many gamesWoWThe WitcherLegend of Grimlock…

Getting it: http://www.lua.org Documentation: http://www.lua.org/docs.html Trivia: “Lua” means moon in Portugese

Our Intro’s steps (one lecture / mini-lab each

/ quiz for each)

1. Get familiar with the non-OOP features (this lecture)

2. OOP-esque programming in Lua

3. Writing a C extension to Lua

4. Embedding Lua in a C program.

5. Integrate Lua into our Engine

Note: We’re NOT going to cover a significant amount of Lua. We’ll just look at enough to get started – then it’s up to you!

Running Lua programs

For now…Create a .lua (text) file in Notepad++Run through the command line

Eventually…No command-prompt.We’ll make ssuge contain an embedded

Lua interpreter which works with our C/C++ code.

Simple example (sample01.lua)print(“Hello, World”) -- it has to be this…:-)

save it to sample01.lua (mine is in c:\Shawnee\2014sp\etgg3802\lua)

run “cmd” from the start menu

Something a little more exciting (sample02.lua)

-- defines a new factorial functionfunction fact(n)

if n == 0 thenreturn 1

elsereturn n * fact(n - 1)

endend

print("Enter a number: ")a = io.read("*number") -- could also be ... -- [no args] waits for enter -- "*all" reads file contents(not useful here)

-- "*line" reads a line of text -- n reads n (int) characters

print(a .. "! = " .. fact(a)) -- concatenation with auto-conversion

Lua types These are the only built-in constructs in Lua

nil (a non-value; useful to indicate garbage)booleansnumbers (doubles, (sort of) int’s)strings (ascii 8-bit)tables (the biggie)functionsuserdata (we’ll see these when embedding)threads (we won’t cover these)

Note: no classes, but we can use tables to do OOP.

string examples (sample03.lua)x = "This is a \"test\""print(x)y = string.gsub(x, "test", "quiz")print(y) -- “This is a “quiz””

z = [[This is a really longstring coveringfour lines]]print(z) -- useful for a block "comment"

q = [==[Another multi-linetext]==]-- This is necessary because sometimes we'll use [[ and ]]-- for other things. e.g. a = b[c[i]] (list-like access)-- You can have any number of '=' characters.print(q)

r = string.rep(“abc”, 3) print(r) -- abcabcabc

string examples, cont.

print("10" + 1) -- "11"print("10 + 1") -- "10 + 1"print("15" * "3") -- "45" (auto-conversion to number)print("-5.3e-10" * "2") -- -1.06e-9 (auto-conversion to number)--print("hello" + 1) -- ERRORprint(10 .. 20) -- "1020" (auto-conversion to string)print(tostring(10) .. tostring(20)) -- "1020" (preferred way)

string examples, cont.print("Enter something: ")response = io.read()n = tonumber(response) -- nil if unconvertableif n == nil then

error("'" .. response .. "' can't be converted to a number")else

print(n * 2)end

xlen = #x -- length of (string) xprint("'" .. x .. "' is " .. xlen .. " characters long")

-- a wrapper for C’s printf functionprint(string.format("[%s, %d::%0.2f]", "hello", 5, 15.37894))

string examples, cont.s = "==qasdlkfjh==slkjh==u=="

-- Extracting a sub-string subs = string.sub(s, 2, 10) -- includes start / end indicies

-- finds the character *after* each ==, if there is oneindx = 1while true do new_indx, end_indx = string.find(s, "==", indx) if new_indx == nil then break elseif end_indx < #s then

print("(" .. new_indx .. ") = " .. string.sub(s, end_indx + 1, end_indx + 1))

end indx = new_indx + 1end

Tables

Nearly everything in Lua is a table. A table is an associative array

A collection of key-value pairs○ Both can be any Lua “thing” (including other

tables!)UnorderedLike a python dictionary or STL (C++) maps

Table example (sample04.lua)

a = {} -- an empty tablea.x = 15a.y = "hello"a.z = 3.7print(a) -- table: 003FC9B0for k, v in pairs(a) do print("key=" .. k .. ", value=" .. v)end

Table example, cont.

a.x = a.x + 1a["x"] = a["x"] + 1 -- same as line beforeprint(a.x)print(a.q) -- nil: a non-existent key (not an error...)

b = a -- Note: a and b are *pointers* to the *same* tableb.y = "goodbye"print(a.y) -- goodbye

Table example, cont.

-- sorting the keys of a tabletemp_keys = {}for k, v in pairs(a) do temp_keys[#temp_keys + 1] = kendtable.sort(temp_keys)for _, v in pairs(temp_keys) do -- _ is a "don't-care" variable print("a[" .. v .. "] = " .. a[v])end

Table example, cont.

-- creating a table with (integer) valuesc = {[5] = "abc", [6] = "def"} -- integer keysc[7] = "xyz" -- new int keyfor i = 5, 7 do print(c[i])end-- Looks a lot like an array, doesn't it...-- ...in fact there is NO array type in lua. This is it!

Table example, cont.

-- lua "lists" start with index 1 by convention.d = {}for i = 1, 10 do d[i] = i * i + 2endprint(#d) -- 10 (length -- only works for 1-based "lists")print(d[#d]) -- 102 (last element)

print(d[10]) -- 102print(d["10"]) -- nilprint(d["+10"]) -- nil (not the same key as "10")

Table example, cont.

-- table with table values (a 2d table)times_table = {}for i = 1, 10 do times_table[i] = {}

for j = 1, 10 do times_table[i][j] = i * jend

end-- pull out result for 5 * 7print(times_table[5][7]) -- or times_table[7][5] here

[File] I/O (sample5.lua)

(This is the more general method)And a taste of OOP in Lua

-- Wrapping in the assert call will fail if io.open returns nil (error)local f = assert(io.open("test.txt", "r"))

count = 1while true do -- Note the colon here. f is an "object" and we're calling -- the read "method" L = f:read("*line") -- reads one line of text. Could also be -- "*all": reads entire file

-- n: Reads n characters if L == nil then break end print("Line #" .. count .. " = '" .. L .. "'") count = count + 1endf:close()

local vs. global variables

Normally all variables are global.Regardless of where they're defined

Put the local keyword before the name when creating to limit it to that block

It's good practice to use locals to hide "unncessary" variablesEncapsulation

local example (sample06.lua)x = 10 -- a global

function foo() y = 99 -- also a global print(x) -- 10

local x = 11print(x) -- 11 (masks the global x)if x < 50 then local x = 12

print(x) -- 12 masks the local aboveendprint(x) -- 11 (the 12 is no longer masking)

end

foo()print(x) -- 10 (function locals are gone)

command-line args

An alternate way to call lua from command line:

lua script_name.lua arg1 arg2 …

lua sample1_07.lua 5 3.2 abc

-- command-line arguments testfor i, val in pairs(arg) do print("arg#" .. i .. " = '" .. val .. "'")end