Please feel free to make comments about the tutorial on this page. If you are new to wikis you may want to have a look at WikiHelp for some pointers about what to do to use and edit this wiki.
Notes by author: If you have a critical comment to make, please put forward a way of correcting the criticism. E.g. if you think a topic is missing or you would like to see more examples. Please make positive noises as well. If the structure and style of the tutorial is liked then it may be extended further (and the author will feel his efforts are worth while!). Thanks.
Add comments below:
- Personally, thought the existing tutorials are great, I'd like to see a basic example of say how to open a window. This might seem easy to some of the more competent coders but for those just starting it would be a great help.
- Lua has been designed for portability to many platforms, some of which do not have windows, or even filing systems. It follows that core Lua cannot open windows or scan directories, or anything which is OS-specific. Of course, implementations of Lua for a particular platform may have libraries that address such specific matters. Your question would be better addressed to a forum devoted to a particular implementation, because there will be different answers for each.
- It would be useful to have links to move to the next/previous topic at the bottom of each page. This would permit one (me?) to read/scan the wiki's content more effectively. --JimE
- I'm fairly new to programming in general and I'd first of all like to say that so far what I've read (all of the introduction tutorials) has been pretty clear and easy to understand. However I did feel in the expressions tutorial that I was missing out on what I needed to know to understand parts of it. Specifically I'm talking about the operator "or" when it gets into implementing it into functions. I don't think any of the previous tutorials covered such things like "local value" and the rest I found just plain confusing in the section covering "or". A little more explaination in that area would be great. Sorry, this may seem nitpicky on my part, but when I don't understand something I feel like I must have missed a large bit of information I should know. Thanks.
- Much needed content presented in an easy to read format. I sincerly hope the content stays focussed on Lua 5.0 and not go into the differences between previous versions (except when it helps even the seasoned Lua programmers). My $0.02 would be to move all the page links of (i.e Lua 5.0) tutorials to a new page titled Lua 5.0 tutorials. Thank you.
- Thanks very much for the feedback. I have a feeling this wiki could get very confused if we all start trying to have pages supporting multiple versions. I'd assume that when each "official version" of Lua comes out, all of the content is updated, as there is no reason to support the old content (as the new Lua is better!). I agree things could get confusing if we start mentioning the differences. It's already a little confused as we have a mixed content site. We should probably label Lua 4 stuff thus and update it if necessary and appropriate. I've tried hard to aim for clarity and I'm sure Lua users can work out the differences. I think the LuaFiveFeatures page covers any changes so we'll leave those there and perhaps I should add a link in somewhere. --NDT
- Need C examples. Specifically, how do I pass args to lua scripts, get return values from them, and how to register a C function to be called from a lua script, and how to call a lua script function from C? Everything I see here focuses on the lua syntax.
- Correct, as pointed out in the LuaTutorial notes: "Note to programmers wanting to embed Lua: Please note that this tutorial is aimed at usage of the scripting language, rather than the C API for embedding. A tutorial for usage of the C API may be added at a later date." The reason for this is that the authors immediate target audience are script users, not embedders. I would like to extend the tutorial in the future though, once the syntax tutorial is complete. There are numerous examples of usage of the API on the wiki and invarious Lua projects, e.g. BindingCodeToLua, VectorLibrarySample, SimpleCppBinding, SimplerCppBinding, LuaCheia, DorisViewer, and see SampleCode. Thank you for your comments. --NDT
- I just want to join in for some positive feedback. It was great to find example code showing how to bind Lua and C++ together, and by that have a starting point for further investigations of the Lua C API. I've found quite a bit of information in the documentation, but the good example is the best way for me to really understand what is happening. Thank you. --Andreas
- I am having my first exposure to the Lua programming language and this wiki is really proving to be very useful. I've read above about the advantages of not trying to cover every single version of Lua, but focusing on the current one (5.2.1), but wouldn't be nice that it is made explicit at the tutorial? My first try has taken me to a Lua 4.0 build for DJGPP and when I tried to follow the tutorial I immediately found the differences: (1) no support for
= expression
, (2) true
and false
are undefined and turn into nil
. Unaware it scared me at first, then I've realized it was really necessary to use Lua 5.0. What about if the tutorial included in a visible place something like this:
- Note. This tutorial is oriented to the current release of Lua (actually, Lua 5.2.1). Using older versions, it is possible that a couple of things looks strange at first. See LuaFiveFeatures.
- It does say this (almost exactly) on the LuaTutorial page, twice, also in TutorialExamples. I'll put a mention in the TutorialDirectory. --NickTrout
- Thanks and congratulations. Lua and this wiki are really nice. --Adriano R. Ferreira
- I'm just beginning to learn lua, and I think it would be useful to have the entire tutorial in a downloadable format. Is this doable? -- Arun
- As the tutorial may make various links to other pages in the wiki, you might end up having to duplicate the whole wiki. JohnBelmonte's page shows how to use the unix
wget
utility to make a static copy of the wiki.
- Overall, I found the tutorial very straight-forward. I loved being able to run
lua
in interactive mode and experiment immediately. I appreciated the simple, minimal Wiki page layout. Feedback follows. --ShayGreen? --Thanks very much for your thoughtful comments --Nick
- Make clear what a block is and where newlines can go, up-front (again, I might have missed mention of this).
- Fair comment, there is nothing really about layout and usage of blocks. Perhaps you would like to add this tutorial page? Perhaps
CodeBlockTutorial?
-- NickTrout
- At the bottom of each tutorial page, a link to the next section would be useful.
- It's not really how the wiki works though. There is some order but only from the index page. There are links to appropriate pages from other pages in the wiki. Over time the wiki will evolve and the "next page" may not make sense any more. -- NDT
- In ControlStructureTutorial, this comment wasn't immediately clear: We can exit the control of a
while
statement using the break
keyword. The break
keyword must be the last statement in a block, i.e. the keyword end
must follow. E.g.,... This comes off clearer for me: ...If break
is used in a block, it must be the last statement in that block before the end
keyword, since anything after a break
is unreachable.
- I don't think we're stating the same thing here. In Lua you cannot have extra commands after break since this generates compilation errors. --NDT
- i think what Shay is trying to say here is "you get a compilation error here *because* anything after a
break
*would* be unreachable".
- if the resulting compilation error would be more helpful (
'end' expected after 'break'
, instead of 'end' expected near 'some_symbol'
) we could remove the mention of this entirely --PeterPrade
- That is what Shay is trying to say, but it is actually correct to say that the syntax requires that
break
(and return
) be at the end of a block. This has the side-effect of avoiding unreachable code, but as has been pointed out to me, sometimes it would be nice to disable some code during debugging. You cannot do that with break
because it would be a syntax error. --RiciLake
- The text mentions "function prototypes" many times, which is strange to someone not coming from a C background. [...] better to exchange "function prototype" with "function declaration" -- AndreiFormiga?
- Thanks for the feedback Andrei. I've removed references to function prototypes and replaced it with more generic language. --NDT
- I couldn't find any explaination of what the ':' operator does, how it differs from '.', as in file:lines vs file.lines -- Confused
- I notice some parts of the tutorial are still in progress. However, I would like to know if there will ever be an "un-wikified" version of the Tutorial. In other words, is the community interested in having the Tutorial mirrored at another site, which is uneditable? This would be akin to how the Python people present its tutorial, and perhaps ease confusion when the Lua version switches, i.e a tutorial geared toward each version can be "frozen". It would also have the advantage of being unspammable. --xlthlx
- Very good tutorial. I wish that there was one of the same caliber for CGILua as I want to use Lua primarily for website development. I have a sense that Lua can out-perform PHP / Perl hands down. Thank you Nick Trout! -- Duke
- [Can] someone please add a chapter explaining Lua 5.1's module system? It would be really helpful. -- Shoaib Meenai
- Yes, that would be needed. There is a good intro to the Lua 5.1 module system in the second edition of Programming in Lua [1]. Actually, Chapter 15: "Modules and Packages" is provided as an excerpt online. That book is well regarded. --DavidManura
- Note that the tutorial was written before the first edition of PIL existed. It certainly filled an important need at the time, but now I'd recommend PIL over the tutorial in almost all cases. --JohnBelmonte
- Yeah, but I don't think PIL 2 is available anywhere in my country (Pakistan) :( -- Shoaib Meenai
- Given the time devoted to what their output values are, ExpressionsTutorial should make mention if 'and' and 'or' are short circuiting. That is, if foo() has a side effect (e.g. printing output), will an expression such as '1 or foo()' or 'nil and foo()' trigger the side effect?
- It will not. 'and' and 'or' are non-strict, i.e. lazy, in their right hand argument.
- I think this is a very good tutorial. But because the Tutorial is for persons (like me) that don't have much experience with scripting languages it would be useful to explain (at the beginning, for example in TutorialExamples) how I can write a script into an editor and run all the commands at once by calling this file. I guess I could run the commands of this file by calling the file like a function after the >-symbol. I will read on in the tutorial and perhaps will find an answer in the later chapters. (I used Lua from the Lua console. I couldn't get luaeclipse (Eclipse plugin for Lua) to work so far. I'm running on Linux so am happy about a suggestion for a good IDE for Lua.)
- Now I realised that it is as simple as this: run "lua filename" (without the quotation marks) on console and it runs just fine. Would be better if it was written in the tutorial directly. I will change that.
Thanks for a very complete tutorial. Well put together and helped with coming quickly up to speed with the language.
In the TableLibraryTutorial section, the following section does not work for the most recent Lua release (5.2) as I understand that many other sections have the same issue. Can you provide and explain what the following sample code would change to so it works with the most recent released version.
table.sort(table [, comp])
> t = { 3,2,5,1,4; n=3 } -- construct a table with user size of 3
> table.sort(t) -- sort will be limited by user size
> = table.concat(t, ", ") -- only specified size is concatenated as well
2, 3, 5
Old Stuff
For lack of a better stuff, here's old Lua 5.0 stuff removed from the Lua 5.1 tutorial.
collectgarbage([limit])
Sets the memory allocation limit at which the garbage collector will be called. If the new limit is less than the current amount of Lua memory allocation, or no argument is given, the collector is called immediately. See the GarbageCollectionTutorial for more information on.
> = gcinfo() -- find current memory stats, i.e. 21kb used
21 35
> bigalloc = string.rep('a', 100000) -- create a big string
> = gcinfo() -- 164kb allocated now
164 327
> collectgarbage() -- force collection
> = gcinfo() -- we did free some memory on collection
139 278
> bigalloc = nil -- release the string we created
> = gcinfo() -- it's not deleted until its collected
140 278
> collectgarbage() -- collect
> = gcinfo() -- it's deleted
29 59
gcinfo()
- TO DO: Returns two results: the number of Kbytes of dynamic memory that Lua is using and the current garbage collector threshold (also in Kbytes).
loadlib(libname, funcname)
This function links the program with the dynamic C library "libname
". Inside this library, it looks for a function "funcname
" and returns this function as a C function. libname
must be the complete file name of the C library, including any eventual path and extension. This function is not supported by ANSI C. As such, it is only available on some platforms (Windows, Linux, Solaris, BSD, plus other Unix systems that support the dlfcn standard).
loadlib
gives you the ability to enhance your lua scripts with self written C functions. The following example should give you some hints if you want to implement your own stuff. This was tested in Linux but should work on other platforms too. You should know how to create shared object libraries. All files in the example should be in the same directory.
/* mylib.c might look like this: */
#include "lua.h"
#include "stdio.h"
/* This function will be exported to lua */
static int lua_myfunc(lua_State* l)
{
printf("blabla");
return 0;
}
/* This function is our Initialization */
int init(lua_State* l)
{
printf("Registering personal functions");
lua_register(l, "myfunc", lua_myfunc);
printf("Done registering");
return 0;
}
Now compile it as a library (in *nix or Cygwin):
gcc -Wall -g -O2 -shared `lua-config --include` -c mylib.c -o mylib.o
gcc mylib.o -Wall -g -O2 -shared `lua-config --include` `lua-config --libs` -o mylib.a
After this you should have a file called mylib.a
, this is our library. Now lets write a simple test script in lua:
luainit = loadlib("./mylib.a", "init")
-- now call the initialization routine
luainit()
print("New registered function: " .. myfunc)
-- start the new function
myfunc()
print("well done.")
- Email support is available from the author of this example @ reflex-2000 <aat> gmx < dottt> net
math.mod
Divide the first argument by the second and return the remainder.
> = math.mod(7,3)
1
> = math.mod(9,3)
0
> = math.mod(100,2.3)
1.1
The table library is explained in section 5.4 of the Reference Manual . There are more details about tables in the TablesTutorial.
The manual is concise about the purpose of this library. We'll quote it here:
- Most functions in the table library assume that the table represents an array or a list. For those functions, an important concept is the size of the array. There are three ways to specify that size:
- the field "
n
" - When the table has a field "n
" with a numerical value, that value is assumed as its size.
-
setn
- You can call the table.setn()
function to explicitly set the size of a table.
- implicit size - Otherwise, the size of the object is one less the first integer index with a
nil
value.
- For more details, see the descriptions of the
table.getn()
and table.setn()
functions.
Note: The size of a table does not necessarily reflect the number of elements contained in the table. This may seem a little strange but it can be useful, for example, for maintaining non-sequential lists.
table.getn(table)
- deprecated for the length operator #
This is used to determine the size of a table. The size of a table is discussed at the top of this page.
> = table.getn({1,2,3}) -- Lua will count the elements if no size is specified
3
> = table.getn({1,2,3; n=10}) -- note, n overrides counting the elements
10
> t = {1,2,3}
> table.setn(t, 10) -- set our own size with setn()
> = table.getn(t)
10
> = table.getn({1,2,3,nil,5,6}) -- sequence ends at element 3 due to nil value at 4
3
table.setn(table, n)
Set the size of a table (see notes on table size and top of this page). If the table has a value "n
" it is updated, e.g.,
> t = { 1,"two","three"; n=10 } -- create a table which has a user size specified
> = table.getn(t) -- read the size
10
> table.foreach(t, print) -- display the elements of the table
1 1
2 two
3 three
n 10
> table.setn(t, 12) -- use setn to change the size
> = table.getn(t) -- display the size
12
> table.foreach(t, print) -- display the table contents
1 1
2 two
3 three
n 12
If the table has no element with the key n
the size of the table is held internally.
> t = { 1,"two",3,4 } -- no "n"
> = table.getn(t) -- calculate the size of the table
4
> table.setn(t, 10) -- set the size to a user defined value
> = table.getn(t) -- find the size
10
> table.foreach(t, print) -- look at the table contents
1 1
2 two
3 3
4 4
RecentChanges · preferences
edit · history
Last edited August 10, 2013 4:50 am GMT (diff)