Documente Academic
Documente Profesional
Documente Cultură
Howtomakeavariablelocal:
localline=io.read()Readsnextstdinline.
Stringconcatenationusesthe..operator:
print('Winteriscoming,'..line)
end
Undefinedvariablesreturnnil.
Thisisnotanerror:
foo=anUnknownVariableNowfoo=nil.
aBoolValue=false
Onlynilandfalsearefalsy;0and''aretrue!
ifnotaBoolValuethenprint('twasfalse')end
'or'and'and'areshortcircuited.
Thisissimilartothea?b:coperatorinC/js:
ans=aBoolValueand'yes'or'no'>'no'
karlSum=0
fori=1,100doTherangeincludesbothends.
karlSum=karlSum+i
end
Use"100,1,1"astherangetocountdown:
fredSum=0
forj=100,1,1dofredSum=fredSum+jend
Ingeneral,therangeisbegin,end[,step].
Anotherloopconstruct:
repeat
print('thewayofthefuture')
num=num1
untilnum==0
2.Functions.
functionfib(n)
ifn<2thenreturn1end
http://tylerneylon.com/a/learnlua/ 2/10
2017628 LearnLuain15Minutes
ifn<2thenreturn1end
returnfib(n2)+fib(n1)
end
Closuresandanonymousfunctionsareok:
functionadder(x)
Thereturnedfunctioniscreatedwhenadderis
called,andremembersthevalueofx:
returnfunction(y)returnx+yend
end
a1=adder(9)
a2=adder(36)
print(a1(16))>25
print(a2(64))>100
Returns,funccalls,andassignmentsallwork
withliststhatmaybemismatchedinlength.
Unmatchedreceiversarenil;
unmatchedsendersarediscarded.
x,y,z=1,2,3,4
Nowx=1,y=2,z=3,and4isthrownaway.
functionbar(a,b,c)
print(a,b,c)
return4,8,15,16,23,42
end
x,y=bar('zaphod')>prints"zaphodnilnil"
Nowx=4,y=8,values15..42arediscarded.
Functionsarefirstclass,maybelocal/global.
Thesearethesame:
functionf(x)returnx*xend
f=function(x)returnx*xend
Andsoarethese:
localfunctiong(x)returnmath.sin(x)end
localg;g=function(x)returnmath.sin(x)end
the'localg'declmakesgselfreferencesok.
Trigfuncsworkinradians,bytheway.
Callswithonestringparamdon'tneedparens:
http://tylerneylon.com/a/learnlua/ 3/10
2017628 LearnLuain15Minutes
Callswithonestringparamdon'tneedparens:
print'hello'Worksfine.
3.Tables.
Tables=Lua'sonlycompounddatastructure;
theyareassociativearrays.
Similartophparraysorjsobjects,theyare
hashlookupdictsthatcanalsobeusedaslists.
Usingtablesasdictionaries/maps:
Dictliteralshavestringkeysbydefault:
t={key1='value1',key2=false}
Stringkeyscanusejslikedotnotation:
print(t.key1)Prints'value1'.
t.newKey={}Addsanewkey/valuepair.
t.key2=nilRemoveskey2fromthetable.
Literalnotationforany(nonnil)valueaskey:
u={['@!#']='qbert',[{}]=1729,[6.28]='tau'}
print(u[6.28])prints"tau"
Keymatchingisbasicallybyvaluefornumbers
andstrings,butbyidentityfortables.
a=u['@!#']Nowa='qbert'.
b=u[{}]Wemightexpect1729,butit'snil:
b=nilsincethelookupfails.Itfails
becausethekeyweusedisnotthesameobject
astheoneusedtostoretheoriginalvalue.So
strings&numbersaremoreportablekeys.
Aonetableparamfunctioncallneedsnoparens:
functionh(x)print(x.key1)end
h{key1='Sonmi~451'}Prints'Sonmi~451'.
forkey,valinpairs(u)doTableiteration.
print(key,val)
end
http://tylerneylon.com/a/learnlua/ 4/10
2017628 LearnLuain15Minutes
_Gisaspecialtableofallglobals.
print(_G['_G']==_G)Prints'true'.
Usingtablesaslists/arrays:
Listliteralsimplicitlysetupintkeys:
v={'value1','value2',1.21,'gigawatts'}
fori=1,#vdo#visthesizeofvforlists.
print(v[i])Indicesstartat1!!SOCRAZY!
end
A'list'isnotarealtype.visjustatable
withconsecutiveintegerkeys,treatedasalist.
3.1Metatablesandmetamethods.
Atablecanhaveametatablethatgivesthetable
operatoroverloadishbehavior.Laterwe'llsee
howmetatablessupportjsprototypeybehavior.
f1={a=1,b=2}Representsthefractiona/b.
f2={a=2,b=3}
Thiswouldfail:
s=f1+f2
metafraction={}
functionmetafraction.__add(f1,f2)
sum={}
sum.b=f1.b*f2.b
sum.a=f1.a*f2.b+f2.a*f1.b
returnsum
end
setmetatable(f1,metafraction)
setmetatable(f2,metafraction)
s=f1+f2call__add(f1,f2)onf1'smetatable
f1,f2havenokeyfortheirmetatable,unlike
prototypesinjs,soyoumustretrieveitasin
getmetatable(f1).Themetatableisanormaltable
http://tylerneylon.com/a/learnlua/ 5/10
2017628 LearnLuain15Minutes
getmetatable(f1).Themetatableisanormaltable
withkeysthatLuaknowsabout,like__add.
Butthenextlinefailssinceshasnometatable:
t=s+s
Classlikepatternsgivenbelowwouldfixthis.
An__indexonametatableoverloadsdotlookups:
defaultFavs={animal='gru',food='donuts'}
myFavs={food='pizza'}
setmetatable(myFavs,{__index=defaultFavs})
eatenBy=myFavs.animalworks!thanks,metatable
Directtablelookupsthatfailwillretryusing
themetatable's__indexvalue,andthisrecurses.
An__indexvaluecanalsobeafunction(tbl,key)
formorecustomizedlookups.
Valuesof__index,add,..arecalledmetamethods.
Fulllist.Hereaisatablewiththemetamethod.
__add(a,b)fora+b
__sub(a,b)forab
__mul(a,b)fora*b
__div(a,b)fora/b
__mod(a,b)fora%b
__pow(a,b)fora^b
__unm(a)fora
__concat(a,b)fora..b
__len(a)for#a
__eq(a,b)fora==b
__lt(a,b)fora<b
__le(a,b)fora<=b
__index(a,b)<fnoratable>fora.b
__newindex(a,b,c)fora.b=c
__call(a,...)fora(...)
3.2Classliketablesandinheritance.
Classesaren'tbuiltin;therearedifferentways
tomakethemusingtablesandmetatables.
http://tylerneylon.com/a/learnlua/ 6/10
2017628 LearnLuain15Minutes
tomakethemusingtablesandmetatables.
Explanationforthisexampleisbelowit.
Dog={}1.
functionDog:new()2.
newObj={sound='woof'}3.
self.__index=self4.
returnsetmetatable(newObj,self)5.
end
functionDog:makeSound()6.
print('Isay'..self.sound)
end
mrDog=Dog:new()7.
mrDog:makeSound()'Isaywoof'8.
1.Dogactslikeaclass;it'sreallyatable.
2.functiontablename:fn(...)isthesameas
functiontablename.fn(self,...)
The:justaddsafirstargcalledself.
Read7&8belowforhowselfgetsitsvalue.
3.newObjwillbeaninstanceofclassDog.
4.self=theclassbeinginstantiated.Often
self=Dog,butinheritancecanchangeit.
newObjgetsself'sfunctionswhenwesetboth
newObj'smetatableandself's__indextoself.
5.Reminder:setmetatablereturnsitsfirstarg.
6.The:worksasin2,butthistimeweexpect
selftobeaninstanceinsteadofaclass.
7.SameasDog.new(Dog),soself=Doginnew().
8.SameasmrDog.makeSound(mrDog);self=mrDog.
Inheritanceexample:
LoudDog=Dog:new()1.
functionLoudDog:makeSound()
s=self.sound..''2.
print(s..s..s)
http://tylerneylon.com/a/learnlua/ 7/10
2017628 LearnLuain15Minutes
print(s..s..s)
end
seymour=LoudDog:new()3.
seymour:makeSound()'woofwoofwoof'4.
1.LoudDoggetsDog'smethodsandvariables.
2.selfhasa'sound'keyfromnew(),see3.
3.SameasLoudDog.new(LoudDog),andconvertedto
Dog.new(LoudDog)asLoudDoghasno'new'key,
butdoeshave__index=Dogonitsmetatable.
Result:seymour'smetatableisLoudDog,and
LoudDog.__index=LoudDog.Soseymour.keywill
=seymour.key,LoudDog.key,Dog.key,whichever
tableisthefirstwiththegivenkey.
4.The'makeSound'keyisfoundinLoudDog;this
isthesameasLoudDog.makeSound(seymour).
Ifneeded,asubclass'snew()islikethebase's:
functionLoudDog:new()
newObj={}
setupnewObj
self.__index=self
returnsetmetatable(newObj,self)
end
4.Modules.
[[I'mcommentingoutthissectionsotherestof
thisscriptremainsrunnable.
Supposethefilemod.lualookslikethis:
localM={}
localfunctionsayMyName()
print('Hrunkner')
end
functionM.sayHello()
print('Whyhellothere')
sayMyName()
end
http://tylerneylon.com/a/learnlua/ 8/10
2017628 LearnLuain15Minutes
end
returnM
Anotherfilecanusemod.lua'sfunctionality:
localmod=require('mod')Runthefilemod.lua.
requireisthestandardwaytoincludemodules.
requireactslike:(ifnotcached;seebelow)
localmod=(function()
<contentsofmod.lua>
end)()
It'slikemod.luaisafunctionbody,sothat
localsinsidemod.luaareinvisibleoutsideit.
Thisworksbecausemodhere=Minmod.lua:
mod.sayHello()SayshellotoHrunkner.
Thisiswrong;sayMyNameonlyexistsinmod.lua:
mod.sayMyName()error
require'sreturnvaluesarecachedsoafileis
runatmostonce,evenwhenrequire'dmanytimes.
Supposemod2.luacontains"print('Hi!')".
locala=require('mod2')PrintsHi!
localb=require('mod2')Doesn'tprint;a=b.
dofileislikerequirewithoutcaching:
dofile('mod2.lua')>Hi!
dofile('mod2.lua')>Hi!(runsitagain)
loadfileloadsaluafilebutdoesn'trunityet.
f=loadfile('mod2.lua')Callf()torunit.
loadstringisloadfileforstrings.
g=loadstring('print(343)')Returnsafunction.
g()Printsout343;nothingprintedbeforenow.
]]
5.References.
http://tylerneylon.com/a/learnlua/ 9/10
2017628 LearnLuain15Minutes
[[
IwasexcitedtolearnLuasoIcouldmakegames
withtheLve2Dgameengine.That'sthewhy.
IstartedwithBlackBulletIV'sLuaforprogrammers.
NextIreadtheofficialProgramminginLuabook.
That'sthehow.
ItmightbehelpfultocheckouttheLuashort
referenceonluausers.org.
Themaintopicsnotcoveredarestandardlibraries:
*stringlibrary
*tablelibrary
*mathlibrary
*iolibrary
*oslibrary
Bytheway,thisentirefileisvalidLua;saveit
aslearn.luaandrunitwith"lualearn.lua"!
Thiswasfirstwrittenfortylerneylon.com.It's
alsoavailableasagithubgist.Tutorialsforother
languages,inthesamestyleasthisone,arehere:
http://learnxinyminutes.com/
HavefunwithLua!
]]
Tyler Neylon
336.2013
http://tylerneylon.com/a/learnlua/ 10/10