This repository has been archived by the owner on Dec 25, 2022. It is now read-only.
Permalink
Cannot retrieve contributors at this time
Name already in use
A tag already exists with the provided branch name. Many Git commands accept both tag and branch names, so creating this branch may cause unexpected behavior. Are you sure you want to create this branch?
lua-snippets/table-import.lua
Go to fileThis commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
executable file
43 lines (34 sloc)
1.06 KB
This file contains 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
| #!/usr/bin/env lua | |
| -- table.import(_ENV, string) | |
| -- table.import(_ENV, string, 's') | |
| -- table.import(_ENV, string, { 'reverse', 'byte' }) | |
| -- table.import(_ENV, string, 's', { 'reverse', 'byte' }) | |
| local is_empty = | |
| function (self) | |
| return not next(self) | |
| end | |
| table.import = | |
| function (self, from, pref, keys) | |
| if type(pref) == 'table' then | |
| pref, keys = keys, pref | |
| end | |
| pref = pref or '' | |
| keys = keys or {} | |
| -- do we import everything? | |
| if is_empty(keys) then | |
| for k, v in pairs(from) do | |
| self[pref .. k] = v | |
| end | |
| else | |
| for _, k in pairs(keys) do | |
| self[pref .. k] = from[k] | |
| end | |
| end | |
| return self | |
| end | |
| assert(string.reverse == table.import({}, string ).reverse ) | |
| assert(string.reverse == table.import({}, string, 's').sreverse ) | |
| assert(nil == table.import({}, string, { 'reverse' }).byte ) | |
| assert(string.reverse == table.import({}, string, 's', { 'reverse' }).sreverse) | |
| table.import(_ENV, string, 's', { 'reverse', 'rep', 'sub' }) | |
| print(sreverse('cat'), srep('donut', 5), ssub('abcdefg', 3, 6)) |