mirror of
https://github.com/extreme-tech-seminar/seven-more-languages-in-seven-weeks.git
synced 2024-11-21 19:18:44 +00:00
5.9 KiB
5.9 KiB
Seven More Languages in Seven Weeks
Introduction
Introduction
Lua BMCOL
LUA
A powerful, fast, lightweight, embeddable scripting language
Indiana Jones BMCOL
Day 1
Day 1: The Call to Adventure
- Installing Lua
-
Exploring with the REPL
- Syntax
- Types
- Functions
Syntax
Whitespace doesn't matter
Types
- Lua is dynamically typed
- No integers (all numbers are 64-bit floats)
nil
is its own type
Functions
- Functions are first-class values
- Arguments are flexible
- Support arbitrary numbers of arguments
- Support arbitrary numbers of results
- Lua does tail call optimization
Variables
Lua variables are global by default
Excercises
Day 2
Day 2: Tables All the Way Down
Tables as Dictionaries
book = {
title = "Grail Diary",
author = "Henry Jones",
pages = 100
}
book.stars = 5
book.author = "Henry Jones, Sr."
Tables as Arrays
- Lua counts array indices starting at 1
medals = {
"gold",
"silver",
"bronze"
}
medals[4] = "lead"
Metatables
Left BMCOL
function table_to_string(t)
local result = {}
for k, v in pairs(t) do
result[#result + 1] = k .. ": " .. v
end
return table.concat(result, "\n")
end
greek_numbers = {
ena = "one",
dyo = "two",
tria = "three"
}
mt = {
__tostring = table_to_string
}
setmetatable(greek_numbers, mt)
Right BMCOL
> =greek_numbers ena: one tria: three dyo: two
OOP
Left BMCOL
Villain = {
health = 100,
new = function(self, name)
local obj = {
name = name,
health = self.health
}
setmetatable(obj, self)
self.__index = self
return obj
end,
take_hit = function(self)
self.health = self.health - 10
end
}
Right BMCOL
SuperVillain = Villain.new(Villain)
function SuperVillain.take_hit(self)
-- Haha, armor!
self.health = self.health - 5
end
SuperVillain:new("Toht")
Coroutines
You may be wondering how Lua handles multithreading.
It doesn't.
Coroutines
Generator B_example
function fibonacci()
local m = 1
local n = 1
while true do
coroutine.yield(m)
m, n = n, m + n
end
end
generator = coroutine.create(fibonacci)
succeeded, value = coroutine.resume(generator)
-- value = 1
Multitasking
Example: Building a Scheduler
Excercises
Exercises
Day 3
Day 3: Lua and the World
Example: Making Music
Excercises
Exercises
Wrapping Up
Wrapping Up
A lot of programmers see the surface of Lua’s clean syntax and assume it’s just another everyday scripting language. I certainly had that feeling at first glance. But I hope that as you’ve taken a deeper look at its tables and coroutines, you’ve enjoyed their beauty and simplicity.
Wrapping Up: Strengths
- Approachable
- Portable
- Easily included in other projects
Wrapping Up: Weaknesses
- Batteries not included
- Inefficient string handling
- Quirky
Final Thoughts
Lua’s prototype-based object approach proves that you don’t need classes to build a great object system.