417 points · by mooreds · 3y ago · 231 comments
There is a huge opportunity, IMO, for more players here. Deno definitely has some good gestures toward a this. Wasm though seems like the likely general heir, and will have many different offerings for how to do that (Deno being one!).
Not only; Lua is also an example of excellent language design: a minimum of concepts for a maximum of expressability; it's minimal, complete and elegant.
> Deno definitely has some good gestures toward a this
Lua is much leaner, only ~100k machine code. WAMR looks like a better candidate than Deno, but concerning performance and simplicity it has still to catch up.
https://docs.groovy-lang.org/latest/html/documentation/guide...
When you factor in LuaJIT[1] and the incredible performance/zero-overhead-FFI[2] it really is a neat language.
How timely! Right now I'm learning Lapis [1] by building a toy CRUD app that I plan on deploying to fly.io. Lua reminds me of Go insofar as it's a really "dumb" language. You can't get too cute and there are a few powerful abstractions that let you accomplish a lot. Coming from Python (which is an endless horizon of PEPs and build artifact standards and name mangling and kwargs and... well, you get the idea) it's kind of a breath of fresh air.
As for 1-based indexing: it makes more sense. We're all just used to 0-based because that's how C worked. If you stop and think about it early C was really just a veneer on top of assembly and since addressing an array in memory meant having a pointer to the first element that meant that it was arr[0]. We have no need for this decades later.
I think my favorite one was one that used yield[1] with the parameters being the number of frames to resume the execution of the coroutine. That was used by a number of our game designers to write AI scripting that felt close to literate programming(I.E. "move x, look for player, yield 30, if found player, go here, etc). You could build a whole AI state machine that fit into one page of code and was very easy to follow.
[1] https://www.lua.org/manual/5.1/manual.html#pdf-coroutine.yie...
https://github.com/fanf2/doh101/blob/master/roles/doh101/fil...
There are quite a few embeddable scripting languages [1]. I think these days it's less common to embed a language mostly because there are good high-level languages that applications can be predominantly written in.
https://gist.github.com/matiasinsaurralde/0a4ecf8f3e0d8768b3...
It has strong support for backward and forward compatibility, a great feature for embedding usage to not make your scripts obsolete and generally working in any version of the host application.
I was recently blown away by some ideas that StackBlitz [0] apply based on WebContainers. The idea of a "server in the browser", they allow you to run Node-based environment like that via Wasm.
I've automated my house based on it. It includes everything you may need , from JSON to TLS, email to websockets... all in a tiny 3MB binary, including the Lua interpreter!!
I run it on a Raspberry Pi and the process takes around 3MB of RAM. Just unbelievable comparing to anything like Node.JS or Java which would require a few 100's MB.
EDIT: the Lua Lanes link is broken... the new location seems to be this: https://lualanes.github.io/lanes/
See the tutorials for what it looks like writing a server:
https://makoserver.net/tutorials/
Start with this:
https://makoserver.net/articles/HTML-Forms-and-LSP-for-Begin...
The docs you should read are mostly from the Barracuda Application server, which Mako is built on:
https://realtimelogic.com/ba/doc/?url=lua.html
You can even try this online:
https://tutorial.realtimelogic.com/Lua-Types.lsp
Click on "Okay, Got it" big button and you can follow along the tutorials, edit code on a demo server, which is how I actually developed my stuff... I actually used a mix of the online editor and editing the Lua files via SSH in emacs, via TRAMP. I highly recommmend either approach.
I usually encourage people to remember the practical origins of 0-based arrays when thinking in terms of pointers, where 0-based counting is useful in terms of talking about offsets from a point in memory, as contrasted to 1-based counting where you are primarily talking about quantities of collections.
Lua is a great language. My only wish is that it was easier to do multithreaded work in it. Unfortunately, this is not the case without some significant architectural forethought.
You could also say the same about counting collections. No regular person counts 0... 1... 2... 3... and ends counting N-1. It, too, is a workaround.
Personally I find it very sad that the agnostic approach of Pascal did not prevail. Let the programmer decide what they think fits the situation best and let the compiler deal with the technicalities. This, and I also miss range types... for like 40 years now...
Most programs don't need numeric indexing. They can either treat indices as opaque keys or they can use a foreach loop to avoid touching indices at all (or friends like map, filter, zip, and so forth). Even in an old language like C the only place indices usually matter is in the first line of a for loop. But sometimes you really do need numeric indices, and when you do zero-based indices are almost always cleanest.
Just think of how gnarly a flat 2D array would be if you had to use one-based indices. Gross!
Think about it. Natural language could easily have associated the initial ordinal with 0. Let's call it the Nilth (zeroth is really hard to say).
The nilth element is element 0, the first element is element 1, etc.
The winner of a race is in nilth place. Silver goes to the person who came first. Bronze so second.
You walk in to a building on the nilth floor, climb the stairs to the first floor (that might sound weird to Americans but it's how it works in other parts of the world).
This is probably all sounding crazy to you but it's way more elegant and self-consistent.
Which century is the year 2023 in again?
Way back then, I started with Algol 68, moved on to Turbo Pascal, and finally Fortran (I was young and needed the money). My vectors and arrays started at 1, as was the default, and I do not even know what you allude to. The first element has the index 1. Since there is no zeroth element - neither in language nor in thinking -, starting at 0 is what causes problems. You always have to use a corrective term in your head - the element five elements after the third one has index 7.
Yes, whatever.
arr[idx mod capacity] = 123
Now with 1-based indexing:
arr[(idx-1) mod capacity + 1] = 123
This is absolutely makes it a PITA if you're working with things like bitmaps, blending, or sound mixing. If you only need a language for high-level scripting, then it indeed is not such a big deal.
One issue with using them that way is that some Lua idioms don't work as expected. For example, "for i,v in ipairs(t) do ... end" will start iteration with i=1 and stop when it reaches an index that isn't present. Also the length operator (#) won't work as expected.
However mod itself is doing extra work compared to incrementing a counter by one.
This is pseudocode because I don't use Lua much and I don't have the time to check the syntax now, but it should give the general idea
class CircBuf(size)
buf = new Array(size)
i = 1
add(value)
buf[i] = value
if i == size
i = 1
else
i = i + 1
The relative efficiency boils down to a comparison+increment vs mod on the particular CPU the code is running on. Mod should be a division, unless size is a power of two.What is the first item in this collection? Oh that would be the one in the box marked zero unless it should be in the one marked ... one!
You mention a circular buffer as an outlier but you simply have to decide where it (the buffer) started off life - 0 or 1 or something else. Make sure that when it is defined, everyone agrees on offsets and off you trot.
No it isn't particularly easy but then bitmaps and blending and sound mixing involve some very involved concepts that are way more complicated than sorting array bounds and worrying about where you are on the Magic Roundabout.
No. A circular buffer is just a simple example where you need to go between offsets and locations.
The same theme happens in many similar cases, like directly manipulating bitmaps. E.g. with zero-based indexing into an RGB bitmap:
bitmap[y*width*3 + x*3] = 1
vs. 1-based indexes: bitmap[(y-1)*width*3 + (x-1)*3 + 1] = 1Starting at 1 is a convention:
array = {“hello”, “world”}
print(array[1]) —- displays “hello”
array[0] = “why”
array[2] = “there”
for i=0,2 do print(array[i]) end —- “why” “hello” “there”
As shown by your example, arrays constructed the native way will start at 1. So you're going to need to make your own custom constructor which means additional overhead.
Also, all built-in functions that expects 1-based arrays will completely break:
for _, value in ipairs({[0]="foo", [1]="bar"}) do print(value) end
This will print "bar"And even if you still insist on pushing through all of this friction by handrolling your own stdlib, everything is out of the window once you interact with any external library that you don't control.
There's a very good reason why no one is using this trick. Anything other than 1-based indexing is just undefined behavior.
If the biggest complaint about Lua is 1-based tables, I’d say that’s a compliment to the language indeed.
So much brain power to defend something that existed a long time ago and was adopted as some kind of law of the Universe when there is clearly no good reason to be this way today other than "it's just how it is" and every new programmer has to pass for a quick phase where the 1-based it beaten out of his mind.
I've specifically run into this with OpenResty and JSON processing...
Ultimately, you can use different data structures in Lua... but you'll have to write reams of boilerplate to do it. That's why I'm saying that (unfortunately) it's Lua itself that's a bad fit, not just tables.
for(i=0; i<n; i++)
In Lua you do: for i=1..n
On the Lua case, both the beginning and end of the loop are inclusive.If you have to iterate over n elements, the first syntax is optimized for 0 to n-1, while the second is optimized for the other case. See:
for(i=1; i<=n; i++) // <n becomes <=
for i=0..(n-1) -- ughI’ve made a few small games using these frameworks in the past and as a hobby plan to continue making games with these frameworks, it’s fun!
Harvard also has a nice course on game dev with LÖVE 2D and Unity, CS50. Can be followed online for free [0].
———
[0]: https://www.edx.org/course/cs50s-introduction-to-game-develo...
* no Luarocks
* no native libraries
More details: http://akkartik.name/freewheeling
For native libs it's a wild west and success depends a lot on your environment. Sometimes the lib is being built with -Werror and fails if you're using more recent compiler, sometimes include paths are not resolved correctly using pkgconfig or similar and so on.
That way lies npm and left-pad.
Tools encourage behaviors. I avoid tools that encourage behaviors I want to avoid.
[1] I wouldn't say Lua/Python/Javascript has no types. They just lack types for variables rather than values. Forth, on the other hand, has no types period.
It’s a single file web application engine, and more, in an executable you can run on several OSes and I think even bare metal, but it’s been a while since I looked at it so it’s probably even more awesome today.
I also recommend the excellent ZeroBrane IDE - https://studio.zerobrane.com/
As a Java/Python dev there is something about using such light weight and fast tools like redbean, lua and ZeroBrane that brings a smile to my face.
I use neovim, hammerspoon which can be configured using lua richly. In a world of ever complicated software, I think lua is coming out as a gold standard for configuration files.
Took <15 minutes to integrate it with the build system (FASTBuild), watched a tutorial video[1], and then in another 15 minutes I had it hooked up to configure my application.
The only issue I've come across in practice is lack of immutable tuples that could be used as table keys. I found myself either emulating this with nested tables or creating string identifiers for my multi-valued keys.
You get used to it pretty quickly when the whole language is built around it.
I solved the immutable table thing by encoding my tables to CBOR in the canonical representation. The same table structure always encodes to the same CBOR. I did have to write my own CBOR encoder, though, because the existing art wasn't good enough.
0 - based indexing is better when dealing with pointers. But, none of us do today, (at least directly), and it seems that 0 based indexing is just an artifact of time.
When I used Lua for professional programming, I thought that 1 - based index is just better. I saw my self doing a lot less (-1) calculations.
European buildings are generally 0-indexed: https://en.wikipedia.org/wiki/Storey#Numbering
0-based indexing makes just a much sense at higher level abstractions, aka iterators because there you're more likely to think in distances and ranges than indices, iter.advance(0) => stay where you are, so if iter is at the start, iter+0 is the first element.
For those looking for a GUI library for Lua, check out TekUI. http://tekui.neoscientists.org/index.html
I tested it on various distros without hassle, both on x86 and ARM. It would probably be worth of porting to other languages too.
That's not totally true, it's easy to integrate and fast. But the language semantics and tooling leave a lot to be desired.
I'm hopeful we get an embedded version of another language. Something as easy to embed as lua, but without the lua. I'd much rather write JavaScript or Rust or anything else.
I have a "second part" in the works on this about implementing something a little more advanced in Lua, and some more exploration of Lua's warts.
Great language and great runtime(s)
Want to also raise awareness of TypeScriptToLua, a fantastic TypeScript transpiler for Lua: https://typescripttolua.github.io/
In comparison, CPython often requires to implement most of your code logic as a library and then load it into the interpreter, which is less than ideal.
Very rarely would you have to implement any custom C code aside from what you’d have to do with any other embedded scripting language to deal with the differences between the two languages and/or blender wonkyness.
I’ve also played around with lua embedding a bit — I just like python more so didn’t do anything with it. I do remember that I got it to work as an experiment but I would have had to start writing some serious C code (the kind you claim is unnecessary) to do anything useful with it and I’m pretty sure the maintainer of the game would have been opposed to being able to script things.
But, I’m one of those people who actually enjoys wrapping C libraries to use in python so…
Not javascript.
Not python.
This.
That which educates the young, shapes the future, may the elders like it or not.
The in-the-works Picotron will grow from Pico-8's roots and present a full fantasy computer, with an OS, windowing system, etc. and expands Lua support to the full v5.4 language.
Roblox Lua/Luau tutorials on youtube - millions of views https://www.youtube.com/results?search_query=luau+roblox&sp=...
Luau
https://github.com/Roblox/luau
Roblox wrote a superset of Roblox Lua which is way faster https://luau-lang.org/
Lucas Pope is developing for the platform now https://dukope.itch.io/mars-after-midnight
Really easy, well documented and fun framework that uses Lua.
[0]: https://love2d.org/
While cute, easy to learn and all, I feel like it has kept back the development of nmap scripts. Only a few people are dedicated enough to take the time to learn it.
Then again, I think this has kept the quality of the available scripts high.
Before reading your post, if i were in a situation where I needed to do complex stuff with nmap, i'd just integrate it in a script that would run it multiple times, parse the output etc.
I never imagined it had a scripting language inside itself.
Guessing the only people who know about that are admins in large networks and black or white hat crackers...
* https://manpages.debian.org/sid/nmap/nmap.1.en.html#NMAP_SCR...
> if i were in a situation where I needed to do complex stuff with nmap
Note: I've never been in such a situation. My network admin duties are like 0.5% of my time.
It doesn't have big sponsors.
Java had Sun and Google. Python, Kotlyn and Go have Google. C had AT&T. Basic and C# had Microsoft. Objective-C and Swift had Apple. FORTRAN and Cobol had IBM. Javascript and Rust had Mozilla, ...
Lua has a lot of small sponsors but no big one.
Very few languages succeed just on their merits, without big sponsors.
Lua really unlocks some superpowers with Redis with respect to being able to chain multiple requests into a single call, handle some application logic, etc.
Also worth noting, NetBSD has had lua hooks into their kernel for about 10 years I think.
It's almost 100% regular Lua syntax and compiles to C, so you get the nice syntax plus speed, similar to Crystal/Ruby. It's not perfect but is interesting nonetheless.
Also, if you want a fun way to play with it, see the LÖVE game engine. You can be making your own simple 2D games in next to no time. And I think that's a nice playground for trying out a language.
- https://love2d.org/ - https://love2d.org/wiki/Getting_Started
The main path is to implement with C or C++ bindings to the libraries you want to use and expose them as Lua module. This is the way Lua is supposed to be used.
2. Define your build for the sources (just compile them! No dependencies! Brilliant!) (don't compile lua.c and luac.c if you provide your own main)
3. Integrate with e.g. this main.cpp (if using c++ is your thing, just plain main.c or whatever is binary compatible):
#include <stdio.h>
extern "C" {
#include <lua.h>
#include <lauxlib.h>
#include <lualib.h>
}
// Native function to be called in Lua
static int add_numbers(lua_State* L)
double a = luaL_checknumber(L, 1);
double b = luaL_checknumber(L, 2);
lua_pushnumber(L, a + b);
return 1;
}int main() {
// Instantiate a Lua interpreter
lua_State L = luaL_newstate();
// Load Lua libraries
luaL_openlibs(L);
// Register native function in Lua
lua_register(L, "add_numbers", add_numbers);
// Call native function in Lua
luaL_dostring(L, "result = add_numbers(10, 20)");
// Read out the result of the function application
lua_getglobal(L, "result");
const char* result = lua_tostring(L, -1);
printf("The result is: %s\n", result);
// Define a function in Lua
luaL_dostring(L, "function concatenate_strings(s1, s2) return s1 .. s2 end");
// Call Lua function in native side
luaL_dostring(L, "result = concatenate_strings('Hello, ', 'world!')");
// Read out the result of the function application
lua_getglobal(L, "result");
const char* result2 = lua_tostring(L, -1);
printf("The result is: %s\n", result2);
// Close Lua interpreter
lua_close(L);
return 0;
}I love that so many games use it.
* https://github.com/kikito/middleclass/blob/master/middleclas...
Using OOP, typesetting a hexagonal grid and a symbolic representation of a neural network on top is easier develop, IMO.
A vertex defines a point in 2D space:
* https://github.com/DaveJarvis/keenwrite-themes/blob/main/bos...
An edge connects two vertices:
* https://github.com/DaveJarvis/keenwrite-themes/blob/main/bos...
A graph connects edges:
* https://github.com/DaveJarvis/keenwrite-themes/blob/main/bos...
A priority queue serves for ordering edges by weight of adjoining vertices:
* https://github.com/DaveJarvis/keenwrite-themes/blob/main/bos...
With these concepts in hand, we can typeset a grid and a "neural network" on top:
* https://github.com/DaveJarvis/keenwrite-themes/blob/main/bos...
Here's an example of the output from the first chapter:
* https://i.ibb.co/19DCDZy/ch-1.png
And a later chapter, where the "network" has grown in complexity:
* https://i.ibb.co/ncf16vg/ch-2.png
This is for my near future hard sci-fi book on AGI. I'm looking for alpha readers to give me feedback. See profile for contact details.
P.S.
There's a subtle bug in the code that can result in one or two disconnected vertices. If you spot it, let me know!
Both Smalltalk and APL use 1 based indices so I just find any claim of obvious aesthetic superiority on this issue a little hard to accept without some back up.
If speaking aesthetics the fact that the number of items in your array is equal to the position of the last index item in the array would seem aesthetically superior.
Arguably, one-based indexing is more closed aligned to mathematics tradition. That point about being easier to index the last element helps to iterate backwards over an array. With zero-based indexing, a backwards loop becomes for(i=N-1; i>=0; i--). Yuck.
local gindex = {}
setmetatable(_G, {__index = function(t,k)
local v = gindex[k]
if v == nil then
error("Bad read of global variable " .. tostring(k), 2)
else
return v
end
end, __newindex = function(t,k,v)
error("Bad write of global variable " .. tostring(k), 2)
end})
for k,v in pairs(_G) do
gindex[k] = v
rawset(_G, k, nil)
endReading about Lua when it was newer I could foresee the same thing happening on steroids. Yes, the language itself is simple but what you can do with it - emulate almost any construct in any language - promises confusion. When it comes to readable code, sometimes "less is more" in terms of langauge features.
> ...
> When it comes to readable code, sometimes "less is more" in terms of langauge features.
Please tell me that is meant as satire. There is no sane way to look at C++ and Lua and decide "less is more" would favor C++.
For example, consider Lua's OO. The most obvious inspiration for Lua here was Newtonscript, via Self. They're quite open about it. Newtonscript and Self are prototype-style OO languages done well, as opposed to Javascript, which is a prototype-style OO abomination. Lua advertises itself as being able to do prototype-style OO, all you have to do is make some tweaks to its metatables. But while this stuff is baked into Newtonscript and Self, it is an amazing amount of boilerplate to do it in Lua, to the point of parody. https://www.lua.org/pil/16.1.html
You're not forced to index from 1 and onwards. You can use any range you want to: https://www.lua.org/pil/11.1.html
function Account:new (o)
o = o or {} -- create object if user does not provide one
setmetatable(o, self)
self.__index = self
return o
end
Doesn't seem so bad. Are you referring to something else?