316 points · by marcobambini · 8y ago · 148 comments
He then explained this "dictatorial" behavior is what allowed him to keep the implementation simple and concise over the years. At the time he boasted about the source code being less than 8K LOC, though it has likely increased in recent versions. (I think it was around version 3.) I'd recommend taking a look at the source code, it's truly a C masterpiece.
Prof. Ierusalimschy's was one of the most interesting seminars in my first year. His passion is apparent in the way he talks about Lua's history and current development. Unfortunately I haven't taken any courses with him
As a side note, it's nice to see folks from around here on HN
- Before Lua 5.3 there was no integer type, this makes a lot of things harder than needed in programming, unless you just write high level code.
- Lua trivially departs from standard syntax like ==, !=, zero-based indexes, without good reasons, creating a general feeling of confusion.
- There was an odd idea about what to include by default and what was optional. The lack by default of bit operations makes the language always in need of a trivial library.
- Tables as a single data structure are not ideal for many tasks. Especially the dualism between tables that are indexed by sequential numbers and tables acting as maps. It's a lot more kind to your users to give up with the solely academical ideal of "just one data structure", and give programmers at least an ordered and a map data type, or at least come up with something better than that. Lisp attempt at doing most things with lists was much more successful and clean.
- The stack-based C API is not comfortable to use.
I could continue to be honest, for instance by default you can't type an expression in the REPL and see the value returned. However when the task at hand is to write small scripts for a larger system, the implementation of Lua offers big enough advantages to make it a worthy choice.
Despite its warts lua still feels like a better (imperative, statement-based) scheme than scheme to me. What scheme offers a similar combination of speed and expressiveness for the same conceptual and file-size weight as lua(jit)?
Wrt to repl: the torch7 repl is quite serviceable, so it's worth giving it a try even if you're not into deep learning.
Sounds great, but:
$ luarocks install trepl
Error: No results matching query were found.
Also the torch7 repo[1] mentions:> Torch is not in active developement
Is there a maintained torch7 repl somewhere?
Maybe Pawn or NekoVM.
https://nekovm.org/doc/lua/ https://github.com/compuphase/pawnv Also, everybody loves benchmarks: https://github.com/r-lyeh-archived/scriptorium
I have a different view.
Lua tables are the foundation for just about any conceivable data structure in CS. While you can do a lot with raw tables in Lua, you can also use them to build all kinds of things on top of them, like b-trees. Or an object system (which is a popular hobby among Lua aficionados).
There's a limit to what can and should be built into any base language. Trying to wedge in more container types can cause a bit of difficulty, in my opinion. Python is the classic example here, where you have tuples using parens, arrays using square brackets, and dictionaries using curly brackets. At some level that is clever, but at another level it is a cause of confusion.
My favorite example are arrays in Lua: They are hashtables, but not quite (in the implementation, every hashtable has a separate array region). They look like hashtables, but not quite (there's syntactic sugar to help dealing with them). You can use hashtable-functions on them, but they don't quite work (which is why there are special functions for when you want to treat a hashtable as an array). Hashtables are great for unordered maps and sets, but they're a crappy replacement for ordered sequences.
> Python is the classic example here, where you have tuples using parens, arrays using square brackets, and dictionaries using curly brackets. At some level that is clever, but at another level it is a cause of confusion.
If that confuses you, then the source of the confusion is you not having a clear understanding of the intended semantics of your code or datastructure. Mixing all of that into a single type won't help here.
Tables + metatables mean that pretty much any structure you want is available. Single Inheritance + Interfaces, Multiple Inheritance, Component Based Design are all things I've seen in the wild on shipped products with Lua.
It's a fantastic 'orchestration' language. Coroutines were also invaluable. We used them extensively to script AI behaviors. Our designers(yes, not developers) would write them with "go to X location", yield, "search for players", yield, etc. Was a really compact way to build a FSM that they could understand.
Tables are a basic mechanism for implementing any data structure. That is a qualitatively different statement from saying that tables can replace any data structure. If you need semantics different from what tables immediately provide, you'll need to implement the desired data structure yourself -- but Lua gives you good tools to do that.
> Maybe there’s a better way I don’t know?
You can use `for i, v in ipairs(arr) do ... end` to iterate over an array without worrying about "how far" to iterate. The `ipairs` iterator will determine when it hits the end of the array.
Having taught programming to many people outside of the programming field, one of the biggest sticking points I have found they face early on is calling the 1st thing the 0th thing, instead of just the 1st thing which is what they've been doing their whole lives. This leaves them with the general feeling that programming as a practice is nonsensical and arbitrary (and they're not wrong). It can turn off a lot of people as they grow frustrated by constant off-by-one errors, which tooling doesn't do much to catch.
If Lua wants to be a language for non programmers, 1 based indexing is a good choice imo.
I'm just telling you what hundreds of people have told me. They expect the first thing to be #1. Their words. I dont see how you can call their own experiences invalid.
Your dismissive attitude is another reason why so many non programmers have trouble learning programming.
> The stack-based C API is not comfortable to use.
What is so uncomfortable about it? I think it's absolutely fantastic. There's nothing you can't do with it, and if you really want a heavyweight "magic" binding library you can do that on top of it. But you'll find even then you occasionally need to fall back to the "raw" API.
Another problem I've with the stack API is that it's insecure by default. If you push too many things it will result in a C stack overflow. I'm not sure how much performance this gives, I mean, the inability to grow the stack automatically looks like an optimization matter... But at least, panic when we reach the max stack instead of smashing the C stack.
There are still quite a few places in the code though, where some complex stack operation is happening and each line of C/ObjC is surrounded by a lot of comments that describe the expected state of the stack at each step, and there have been a lot of situations where I've ended up having to sketch the stack on paper as I'm reading code, to figure out why something isn't working.
So, I think I'd say that the C API is not comfortable to use, but it's also not very complicated. It's somehow managed to be simple, but hard, if that makes any sense.
Edit: If anyone cares, our Lua abstraction is all written in ObjC and is called LuaSkin. It lives in the Hammerspoon git repo, but doesn't actually depend on Hammerspoon at all, so could be extracted and used by others (it's MIT licensed). The API docs are: http://www.hammerspoon.org/docs/LuaSkin/Classes/LuaSkin/inde...
The default numeric type (double float) can precisely represent integers up to 2^53. That's ample for most of my purposes. You can even fit x86-64 pointers into them.
Syntax doesn't match C but that doesn't bother me because I'm used to other languages already e.g. Erlang that uses different operators and one-based indexing.
Bit operations are always there in LuaJIT.
The C API does seem awkward to me too but it's superceded by the lovely FFI in LuaJIT.
And this is quite fair. Those are fundamental qualities of a new programming language.
Wasn't the idea to only use lua as a high level scripting language, and drop down into C(++) if you needed to go low level?
I still think it contains some neat ideas and concepts, even though I would never actually use it for something practical.
Having written a ton of networking code in Lua I can tell it has a lot of design defects that most other programming languages have avoided. Especially the deeply embedded one-based indexing and lack of a separate integer type (chars are strings, ints are floats) make it wearing to type any code that has to parse any binary data. Even bit manipulation requires going through the FFI. Considering that Lua is often touted as the optimal lightweight solution in small embedded systems, these features are must-haves.
The builtin string pattern matching library attempts to mimic regular expressions, but bites the user in the leg every time they attempt to use it for anything remotely regex-y. Unfortunately most usual string manipulation seems to revolve around them and the string.gsub function.
The inconvenient string library is also largely irrelevant. The developers call their language eight-bit transparent which in reality means that the programmer needs a separate Unicode library, rendering the whole standard string library mostly useless. One cannot even format UTF-8 text, because the string library doesn't differentiate between characters and bytes.
The official documentation mostly revolves around C bindings. The actual Lua language documentation is provided by another web site that looks like it has been written by an attention-deficit child. Instead of getting to the point, the articles often first provide a list of ways on how not to implement things, or they are actually benchmarks of fifteen different ways to call the standard library to get the same effect. Sometimes, the provided code does not even work – for example, the given XML parser code crashes when it hits one of the error paths.
The small runtime and fast VM do not really matter when the language itself is lacking and requires a metric ton of external libraries to achieve even the simplest things that are possible in standard C and Rust, which provide the same level of performance and better type safety.
One based indexing is just a design choice, while it complicates interoperation, I find it justified as Lua tables are actually hash tables, so it would be weird to model it upon memory offsets. It reminds me that I am only dealing with a hashmap with integers as keys.
Bitwise and UTF-8 string operations are lacking out of the box, but these are arguably too specialized to be expected in a general scripting language. The patterns are a little underpowered compared to other languages, but it is still quite useful. I suggest looking into LPEG for more complicated operations. Lua 5.3 do have some functions to deal with UTF-8 codepoints.
Also, regarding Unicode, I'd rather the PL provide only operations on bytes, and let me decide what "characters" are to be represented. Nearly all PL providing some Unicode facilities fail in different ways, just let me deal with ICU myself if I really need Unicode. Also it is a royal pain in the butt to deal with different encodings, with a language having special "characters" and "strings" constructs.
I don't understand the complaint on documentation. It is one of the most practical and clear technical writing that I have seen, if a little terse. Perhaps you mistook the wiki as the main document? (The Lua language manual is an one-page HTML page.)
One based indexing isn't just about memory offsets or getting used to it, it makes lots of things a nightmare. Like index-math that involves the modulo operator, which will result in zero values, which are invalid for 1-based indexing. Or turning a 2D or 3D index into a 1D index, which now requires completely unnecessary additions or subtractions of 1s. And other index magic that I frequently need for computer graphics and number crunching.
If this is true, and I actually agree with you, then where is Lua actually better than an alternative?
And, while I don't share the specific points of the parent poster, I experienced similar issues with Lua. I found that while the Lua core language itself is small, I had to compile in so much extra stuff to make it useful that it wasn't actually small anymore.
And, once you get large enough that you start demanding big ARM Cortex M4 microcontrollers, Python is now in your scope.
There are entire games built around modding via lua such as gary's mod which similar to a web browser has to download random code from a server. Then there are mods like computercraft/opencomputers for minecraft in which direct file access to the host doesn't make any sense at all because every computer has it's own filesystem.
I just looked up Python's sandboxing capabilities and I can't find anything. All I see is answers like [0] that suggest that it's not trivial.
What about other implementations like pypy that claim to have a sandbox? [1] I can see lots of warnings like "This is not actively maintained."
The lack of mature sandboxing for python makes it impossible to use for the usecases I've described above.
[0] https://stackoverflow.com/questions/3068139/how-can-i-sandbo... [1] http://doc.pypy.org/en/latest/sandbox.html
I think the idea is that most functionality is meant to be provided by the host program. If you want a standalone scripting language, then Lua probably isn't for you.
Why is Lua an oft-recommended programming language for embedded development if one is not allowed to form opinions on the language?
>so it would be weird to model it upon memory offsets
Why does the language provide table constructors {1, 2, 3} that do one-based indexing then? Why is there a table length operator (#) that works on one-based indexes? Why does ipairs work with one-based indexes? A sequential data type (array, list, for some quirky reason named "tables" in lua) is one of the most basic data structures of a programming language. If Lua is supposed to be a scripting language, why should a programmer care about the underlying implementation?
>Bitwise and UTF-8 string operations are lacking out of the box, but these are arguably too specialized to be expected in a general scripting language.
Is Lua a toy or a tool?
>Lua 5.3 do have some functions to deal with UTF-8 codepoints
I welcome you to the real world, where 5.1 is still the latest available release available on too many platforms.
>Perhaps you mistook the wiki as the main document?
Lua-users.org turns up as the first result when you google for documentation.
I have never heard anyone recommend Lua for embedded development. It's an embeddable language in the sense that you can easily embed the entire interpreter in a larger application and extend it. That it happens to be relatively small and easy on memory is a bonus, not a reason to believe that it's a great systems programming language.
I'm not at all surprised that it disappointed you as a language for low level networking code. Most Lua success stories are about its use as a high level glue/scripting/configuration language, letting the application handle the low level code via an API.
Also the documentation provided by lua.org is quite accessible: https://www.lua.org/manual/5.3
What I'd really like is stdlib to provide a Buffer type, as opposed to having to use a table of integers which then gets pushed into a string with chunked calls to string.char(table.unpack(buf, n, n+4096))
Example of what I'm complaining about: https://github.com/serprex/luwa/blob/master/rt/make.lua#L758
So all said I don't disagree with you: Lua can fall short, it doesn't have the community other languages have built up, & the community it has is rather fractured. Like LuaJIT making 5.2 what most call Lua, but also that being an extension language it's hard to upgrade without losing compatibility, so projects like Redis can't upgrade without deprecating 5.2 for a 5.3 version & making some method to signal 5.3 & then eventually removing 5.2 while packaging both in the interim
The "actual Lua language documentation" you refer to probably is the wiki? I agree it is crap.
By all means, stay away from Lua and use Python and Node for new projects; we like that competitive advantage.
I pretty much agree that Lua can survive such throughput, but I question whether Lua can survive the code complexity. I have written about Lua previously on [1] with a vocal conclsion that Lua cannot really handle a large code base (in the order of 10^5 lines), so I like to hear otherwise (hint: I hadn't). That's why...
> By all means, stay away from Lua and use Python and Node for new projects; [...]
...we have ultimately dropped (a heavy duty use of) Lua from all new projects. C# seems to suit our needs (or any other statically & strongly typed languages---obviously excluding C/C++---would probably do).
We have shipped and maintain a series of games built on progressive iterations of the same codebase; we have on the order of 200 KLOCs of Lua in the common "engine" code and tooling, and 200-400 KLOCs additional game-specific code per game. We tend to hit our milestones and performance targets on six platforms, with programmer quality of life way above the game industry "standards" (i.e. we do normal working hours).
Can things be better? Of course, they always can. But om our experience, large-scale use of Lua is not the disaster it usually is assumed/predicted to be.
This is such an unfair point. Lua has a single manual that covers the language, the standard library, and yes, it also covers C FFI (unsurprisingly for an extensibility / scripting language), but FFI actually comes after the language in the docs. And the manual is both very readable and very thorough where it talks about the language - it's quite easy to learn the whole thing just from it alone.
> lack of a separate integer type (chars are strings, ints are floats)
Lua 5.3 introduced integer types. [1]
> Even bit manipulation requires going through the FFI.
LuaJIT includes a bit manipulation library, but its FFI acceleration is optional. Also, Lua 5.3 introduced bitwise operators. [1]
> One cannot even format UTF-8 text
Lua 5.3 introduced "basic utf-8 support" [1] although I am not sure to what extent.
> The official documentation mostly revolves around C bindings. The actual Lua language documentation is provided by another web site that looks like it has been written by an attention-deficit child
Again, I suspect you are criticizing LuaJIT. The actual Lua documentation [2] has never let me down.
5.3 where all this are solved is the most recent stable version -- not what most people have used for the entire history of Lua (and not default in all distros).
Nope, plain old Lua 5.1 which is still the newest one can get on many platforms. You're stuck with what you have, not what was released yesterday.
>The actual Lua documentation has never let me down.
I read the document you linked and found the documentation lacking on anything but basic syntax and C bindings (the chapter on C API comes before the Lua standard library, btw). The standard library function documentation underspecifies parameter types and both return value types and numbers.
I find the Lua Short Reference [1] much more accessible than the official documentation. It has the very same information in a much more readable format.
>Lua 5.3 introduced "basic utf-8 support"
Looking at the documentation you linked, the Unicode support does not integrate with the string library. Walking a UTF-8 string manually character-by-character has never been difficult and Lua 5.3's support doesn't seem to address any other use cases.
[1] http://lua-users.org/files/wiki_insecure/users/thomasl/luare...
Other than that, as others pointed out, most of your complaints are addressed in 5.3.
That's already reason enough for me not to use it. One based indexing caused me so many headaches in the past in Mathematica...
> Even bit manipulation requires going through the FFI
This, and some of the other things, have not been true for years.
make generic local
Provided that you have a GNU compiler toolchain for the target you should have no problem doing this. If you don't I'm sure there's more effort involved, but ultimately Lua can build with any C99 compliant compiler and most C89 compilers (with the caveat that it can't guarantee that there is a 64-bit integer type in C89).How can you say that? The Lua documentation is on par with Kernighan and Ritchie.
I've switched to using Wren for my new projets. Despite not being as mature as lua (you may have to add some functionalities yourself):
* the syntax is much nicer.
* it's simpler/cleaner to embed.
* it's (allegedly) faster if you are running on a platform where it's forbidden to JIT (e.g. iOS).
* Classes in Lua are a hack, and consequently the syntax for them is terrible.
* Using "end" instead of "}". That decreases readability.
* no "+=" or "++" operators.
Edit: If you have a device with enough computing power to run a scripting language interpreter, you can use Python in most cases.
Lua is very dynamic, easy to code for (syntactical quirks aside, I'm talking from a "cognitive load" standpoint) while C and especially Rust are a lot more static, require more careful coding but can result in faster and, at least in the case of Rust, more robust code.
Lua is the type of language you embed in your C app to make it configurable.
The Lua community is small so every bit helps :)
Shameless Plug: https://Luadigest.immortalin.com
What drove me away from Lua is its philosophy of providing minimal tools in which it is possible, but never easy or convenient, to do work in various programming modalities. Polymorphism, namespaces and packages, arrays, unicode... these things all can be done, but require significant head-standing and in many cases a lot of boilerplate. Even proto-style OO, which you would imagine would be Lua's signature feature, involves lots of rigamarole compared to languages (like Newtonscript) where it is baked in and elegant.
I kept wanting Lua to pick a pony.
Throughout my usage of Lua, I've consistently gone back to Lisp, where I could change the language to make inconvenient things convenient when I needed to.
Off topic, but I've always thought that JavaScript and JSON would have been a lot better without the relatively artificial distinction between objects and arrays. Now that there's object shorthand and destructuring, this will never happen, but it was a nice thought for a while.
The array syntax can be thought of as a shorthand where you want the indexes inferred from order instead of having to list them out. There are obviously a few useful methods that you use on arrays but almost all of these will work on any object with a length if you .call or .apply them.
const a = [2,3,…]
a.prop = "hi"
Now whether that's actually something you should be doing is a different matter...(Also on my JS wish list: Killing the use of const for anything besides actual constants.)
You should be using const for everything besides variables that need to get re-assigned.
A PHP array works as a sequential or an associative array; or both at the same time
If you want to look at a large OpenResty/Lua application from a code perspective you could take a look at Kong[1] - which is the most popular public codebase built on top of NGINX/Lua at the moment.
CloudFlare also uses the same stack but most of their codebase is proprietary.
What really makes Nginx/Lua a good combination is primarily LuaJIT[2] support, a much faster implementation of the Lua VM.
[1] - https://github.com/Kong/kong
[2] - http://luajit.org
For me, day 1 productivity is really high, comparable to Nancy, the framework I was using before.
* http://luajit.org/ext_ffi.html
local ffi = require("ffi")
ffi.cdef[[
int printf(const char *fmt, ...);
]]
ffi.C.printf("Hello %s!", "world")
So while, say, Python is "batteries included", LuaJIT is "all the batteries".Using C libraries in regular Lua is fairly easy as well, but LuaJIT is exceptional.
Do you say this because LuaJIT can call shared libraries dynamically? If so, what about ctypes[0]? Is LuaJIT's FFI just easier to use, or does it do something that ctypes can't?
1) The syntax. To specify the types of the FFI functions you you use a DSL that is similar to C declarations. Often you can copy paste function prototypes from ".h" files with very minimal modifications. With ctypes you need to specify the types with Python function calls. See "ffi.cdef": https://luajit.org/ext_ffi.html
2) Performance. If your code is inside a JIT-compiled trace, LuaJIT FFI calls have minimal overhead. They compile down to something very similar to what a C compiler would generate. Ctypes, on the other hand, must "interpret" the FFI calls which adds more runtime overhead (although admittedly this is also true for LuaJIT if your code ends up outside a compiled trace).
The word "configuration" makes repeat performance in that paper, but oddly is entirely missing from this 2018 paper (by the same authors).
Because they seems closely similar to me and Guile is far more clear and effective, at least for my programming skills...
Although I agree it might be difficult to write scripts in C, in the end it might just depend on the core functions that are exposed.
I'm not a fan of C, I prefer python, but I guess I will have less issues when interfacing c code to c++. Python seems quite fat, slow, and too much different than C++.
It depends on your habits. I for one prefer Lua to Python and find it much more pleasurable to code on. There are some things in Python that I like (like the blocks defined by indentation), but overall the language seeems too complex for no reason when coming from lua.
Lua is a small language, it fits in the head with room left over for Python, which is the tool I favor for general-purpose data munging and small OS scripts.
If your case resembles "scripting over a collection of C ABI static or linked libraries" LuaJIT is head and shoulders above the competition. PUC Lua is itself outstanding.
Python is FAT.