Lua is a scripting Programming Language which is designed to be simple
and can be easily embedded. It runs on a Virtual Machine. Variables are
global by default, so local is used to declare a variable as local
to the current scope. It starts index at 1 contrary to most
programming languages.
There are eight types:
- nil
- boolean
- number
- string
- userdata (used to represent C data structures, or blocks of raw memory)
- function
- thread (used for coroutines)
- table (an associative array, and the sole data structure in Lua)
Binary search written in Lua:
function binary_search(array, value)
local low = 1
local high = #array -- # is the length operator
while low <= high do
-- library functions are accessed via the global table
local mid = math.floor((low + high) / 2)
local mid_value = array[mid]
if mid_value < value then
low = mid + 1
elseif mid_value > value then
high = mid - 1
else
return mid
end
end
return nil
end
res = binary_search({2, 4, 6, 8, 9}, 6)
print(res)
3