Tutorial Comments

lua-users home
wiki

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:

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.

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

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

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

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.

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

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

It will not. 'and' and 'or' are non-strict, i.e. lazy, in their right hand argument.

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:
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)