Created
November 8, 2021 17:01
-
-
Save timm/08a8bcb930222a8099c3e3fad44a9692 to your computer and use it in GitHub Desktop.
emulating pythons "import" statement, in lua
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| -- example of function returning a table of names we want to import | |
| function fun1() print(1) end | |
| function fun2() print(2) end | |
| function fun3() print(3) end | |
| function fun4() print(4) end | |
| function fun5() print(5) end | |
| return {fun3=fun3, fun1=fun1, fun2=fun2, funs5=fun5, fun4=fun4} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| -- example on unpacking all in alpha order | |
| -- analogous to "from cc import *" | |
| local get=require"get" | |
| local fun1,fun2,fun3,fun4,fun5=get"cc" | |
| fun5() |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| -- example on unpacking some | |
| -- analogous to "from cc import fun3,fun1" | |
| local get=require"get" | |
| local fun3,fun1=get"cc fun3 fun1" | |
| fun1() |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| -- get"file" : requires the file and unpacks results in alphabetical order | |
| -- get"file thing1 thing2.." : requires the file and unpacks only thing1 thing2 | |
| -- | |
| -- e.g. | |
| -- local get=require"get" | |
| -- local fun5,fun1=get"fun fun5 fun1" -- only returns fun5 and fun1 | |
| -- local fun1,fun2,fun3,fun4,fun5=get"fun" -- everything unpacked in alpha order | |
| local function get(spec) | |
| local gets, keys,out={},{},{} | |
| for get in string.gmatch(spec, "([^ ]+)") do gets[#gets+1]= get end | |
| local results = require(table.remove(gets,1)) | |
| if #gets>0 | |
| then keys= gets | |
| else for key,_ in pairs(results) do keys[#keys+1] = key end | |
| table.sort(keys) | |
| end | |
| for _,key in ipairs(keys) do out[#out+1] = results[key] end | |
| return table.unpack(out) | |
| end | |
| return get |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment