https://github.com/benwiley4000/string-length-the-hard-way
What if you wanted to get the length of a string in Lua.. the hard way?
https://github.com/benwiley4000/string-length-the-hard-way
lua pico-8 pico8 string
Last synced: 12 months ago
JSON representation
What if you wanted to get the length of a string in Lua.. the hard way?
- Host: GitHub
- URL: https://github.com/benwiley4000/string-length-the-hard-way
- Owner: benwiley4000
- License: mit
- Created: 2019-05-26T20:55:42.000Z (about 7 years ago)
- Default Branch: master
- Last Pushed: 2019-05-26T21:00:44.000Z (about 7 years ago)
- Last Synced: 2025-02-24T10:49:31.375Z (over 1 year ago)
- Topics: lua, pico-8, pico8, string
- Homepage:
- Size: 1.95 KB
- Stars: 1
- Watchers: 3
- Forks: 1
- Open Issues: 0
-
Metadata Files:
- Readme: README.md
- License: LICENSE
Awesome Lists containing this project
README
# string-length-the-hard-way
What if you wanted to get the length of a string in Lua.. without using the `string.len` function or the length (`#`) operator? And make it run in either the standard Lua interpeter or in PICO-8?
Don't ask me why I tried to do this...
```lua
-- PICO-8 and Standard Lua lib compatibility
local _sub = string and string.sub or sub
local _flr = math and math.floor or flr
function string_length(str)
-- we have undefined behavior if the
-- data size is larger than this
-- (max number in PICO-8)
local search_max = 32767
local search_min = 1
-- binary search for index before empty string
while true do
local i = search_min + _flr((search_max + 1 - search_min) / 2)
local char = _sub(str, i, i)
if char == "" then
search_max = i - 1
else
local after = i + 1
local char_after = _sub(str, after, after)
if char_after == "" then
return i
end
search_min = after
end
end
end
```
And it works!
```lua
string_length("hello world") -- 11
```