Peer-reviewed code snippets that anyone can edit
follow refactory on twitter
blog
feedback
A wiki for useful code snippets
Bugs? Suggestions?
38-107-191-111
create/login
options
RECENT
STUBS/REQUESTS
STARRED
ACTIVITY
ADD
VIEW
EDIT
HISTORY
FORK
Lua for Pythoners - Lists
lua
lists
Your work won't be attributed to you
because you aren't logged in.
Login using OpenID or an existing username, or create a username
(no email required) before posting.
Languages
Comma separated. Like
ruby, rails
or
java, swing
Keywords
Comma separated. Like
file, network
Mark as stub
Snippet
Wrap code in
[code=
language
][/code]
- Use
WikiText markup
outside of [code] tags
[code=lua] -- Using Lua standard libraries and Penlight (http://luaforge.net/frs/?group_id=450) -- List catalog: http://www.java2s.com/Code/Python/List/CatalogList.htm package.path=package.path..';./?/init.lua' require 'pl' stringx.import() function string:totable() return seq.copy(seq.map (function (x) return self:at(x) end, seq.range(1,#self))) end function List:__mul (n) res = List() for i=1,n do res:extend (self) end return res end print ("===List") print ("==List Declaration") print ("=Lists can be written as a list of comma-separated values (items) between square brackets.") a = List {'spam', 'eggs', 100, 1234} print (a) print ("==List Append") print ("=Adding elements to lists") li = List {'a', 'b', 'mpilgrim', 'z', 'example'} li:insert (2, "new") print (li) print ("=Append element to a list") scores = List {"1","2","3"} -- add a score io.write("What score did you get?: ") score = tonumber(io.read()) scores:append (score) -- list high-score table for score in scores:iter() do print (score) end print ("=List append(x)") a = {66.25, 333, 333, 1, 1234.5} table.insert (a, 333) print (unpack(a)) print ("=List: The Difference Between Extend and Append") li = List {'a', 'b', 'c'} li:extend {'d', 'e', 'f'} print (li) print (#li) print (li[#li]) li = List {'a', 'b', 'c'} li:append (List {'d', 'e', 'f'}) print (li) print (#li) print (li[#li]) print ("==List Intersect") print ("=Define function to intersect Strings and lists") function intersect(seq1, seq2) if type(seq1) == 'string' then seq1 = seq1:totable() end if type(seq2) == 'string' then seq2 = seq2:totable() end res = {} -- start empty for x in seq.iter(seq1) do -- scan seq1 if tablex.find(seq2,x) then -- common item? table.insert(res,x) -- add to end end end return res end s1 = "SPAM" s2 = "SCAM" print (unpack(intersect(s1, s2))) -- strings s1 = {1,2,3,4,5} s2 = {3,4,5,6,7} print (unpack(intersect(s1, s2))) -- list print ("=Function to intersect two lists") function intersect(seq1, seq2) res = {} -- start empty for x in seq.iter(seq1) do -- scan seq1 if tablex.find(seq2,x) then -- common item? table.insert(res,x) -- add to end end end return res end x = intersect({1, 2, 3}, {1, 4}) -- mixed types print (unpack(x)) -- saved result object print ("==List Reverse") print ("=List reverse(): Reverse the elements of the list, in place") a = List {66.25, 333, 333, 1, 1234.5} a:reverse() print (a) print ("=Sort and reverse elements in list") scores = List {"1","2","3"} scores:sort() for score in scores:iter() do print (score) end scores:reverse() -- want the highest number first -- list high-score table for score in scores:iter() do print (score) end print ("==Variables in List") print ("=Variables in a list") X = {1, 2, 3} L = {'a', X, 'b'} -- embed references to X's object D = {x=X, y=2} X[1] = 'surprise' -- changes all three references! print (pretty.write(L)) print (pretty.write(D)) print ("==List Assign") print ("=Assign list to a list item") L = List {'Already', 'got', 'one'} L:slice_assign(2,nil,{}) print (L) L[1] = List() print (L) print ("==List Filter") print ("=Introducing List Filtering") li = List {"a", "mpilgrim", "foo", "b", "c", "b", "d", "d"} print (li:filter (function(x) return #x>1 end)) print (li:filter (function(x) return x~='b' end)) print (li:filter (function(x) return li:count(x)==1 end)) print ("==List concatenation") print ("=Concatenate two lists") inventory = List {"sword", "armor", "shield", "healing potion"} chest = List {"gold", "gems"} print ("You find a chest which contains:") print (chest) print ("You add the contents of the chest to your inventory.") inventory = inventory .. chest print ("Your inventory is now:") print (inventory) print ("==List In") print ("=Use in to check Membership ") permissions = 'rw' print (permissions:find ('w') and true or false) print (permissions:find ('x') and true or false) users = {'mlh', 'foo', 'bar'} print (tablex.find(users, 'foo') and true or false) print ("==List Loop") print ("=List for iteration") for _,x in pairs({1, 2, 3}) do io.write(x..' ') end -- iteration print ("=To iterate over the indices of a sequence, combine range() and len()") a = {'Mary', 'had', 'a', 'little', 'lamb'} for i,v in pairs(a) do print (i, v) end print ("==List Sort") print ("=Sort elements in a list") L = List {'spam', 'Spam', 'SPAM!'} print (L:append('please')) -- append method call L:sort() -- sort list items ('S' < 'e') print (L) print ("==List Compare") print ("=List equivalent?, same object?") L1 = List {1, List {'a', 3}} -- same value, unique objects L2 = List {1, List {'a', 3}} print (L1 == L2, rawequal(L1, L2)) -- equivalent?, same object? print ("=Same Object or identical content") S1 = 'spam' S2 = 'spam' print (S1 == S2, rawequal(S1, S2)) S1 = 'a longer string' S2 = 'a longer string' print (S1 == S2, rawequal(S1, S2)) print ("=List: less,equal,greater: tuple of results") -- Penlight doesn't implement list compare print ("==List Comprehensive") print ("=List comprehensions: for and tuple") C = comprehension.new() print(unpack(C "x..y for x for y" (('spam'):totable(), ('SPAM'):totable()))) print(unpack(C "List {x,y} for x=0,4 for y=0,4 if x%2==0 if y%2==1" ())) print ("=Find Prime numbers using list") C = comprehension.new() noprimes = C "j for i=2,8 for j=i*2,50,i" () primes = C "x for x=2,50 if not tablex.find(_1,x)" (noprimes) print (unpack(primes)) print ("=List Comprehensions in buildConnectionString, Step by Step") params = {["Key 1"]="value 1", ["key 2"]="value 2", ["key 3"]="value 3", ["key 4"]="value 4"} print (unpack(tablex.pairmap (function(k,v) return k end, params))) print (unpack(tablex.pairmap (function(k,v) return v end, params))) print (unpack(tablex.pairmap (function(k,v) return ("%s=%s"):format(k, v) end, params))) print ("==List Indexing") print ("=List offset: start at zero, negative and slicing") L = List {'spam', 'Spam', 'SPAM!'} print (L[3]) -- offsets start at zero print (L:slice(-2,-2)[1]) -- negative: count from the right print (L:slice(2)) -- slicing fetches sections print ("=Searching a list for an integer.") -- Create a list of even integers 0 to 198 aList = List {} for i=0,199,2 do aList:append (i) end io.write("Enter integer search key: ") searchKey = tonumber(io.read ()) if aList:contains (searchKey) then print ("Found at index:", aList:index (searchKey)) else print ("Value not found") end print ("=Reference index in a list in Python.") foo = List {42, 'www.java2s.com', function(x) return x^2 end, List {47, '11'}} print (foo) print (foo[4]) print (foo[3](3)) foo[4][1] = 99 print (foo) for i in foo:iter() do print (i, "--", type(i)) end print ("==List Remove") print ("=List Delete: delete one item and delete an entire section") L = List {'SPAM!', 'eat', 'more', 'please'} L:remove(1) -- delete one item print (L) L:chop(2) -- delete an entire section print (L) print ("=Deleting List Elements") li = List {'a', 'b', 'new', 'mpilgrim', 'z', 'example', 'new', 'two', 'elements'} print (li:remove_value("z")) print (li) li:remove_value("new") print (li) li:remove_value("z") print (li) print ("==List Count") print ("=List count(x)") -- Return the number of times x appears in the list. a = List {66.25, 333, 333, 1, 1234.5} print (a:count(333)) print ("==List Empty/List repetition") print ("=Empty list multiply/List repetition") L = List {0} * 100 print (L) print ("==List Pop") print ("=Using Lists as Stacks") stack = List {3, 4, 5} stack:push(6) stack:push(7) print (stack) stack:pop() print (stack) print (stack:pop()) print (stack:pop()) print (stack) print ("==List Two Dimension") print ("=Nested list: two dimensions") matrix = {{1, 2, 3}, {4, 5, 6}, {7, 8, 9}} print (unpack(matrix[2])) print (matrix[2][2]) print (matrix[3][1]) print ("=Check a user name and PIN code") database = List { List {'A', '1234'}, List {'B', '4242'}, List {'C', '7524'}, List {'D', '9843'} } io.write ("User name: ") username = io.read() io.write ("PIN code: ") pin = io.read() if database:contains(List {username, pin}) then print ("Access granted") end print ("==Return List") print ("=A function that returns a list of the numbers of the Fibonacci series") function fib2(n) -- return Fibonacci series up to n -- Return a list containing the Fibonacci series up to n. result = List {} a, b = 0, 1 while b < n do result:append(b) -- see below a, b = b, a+b end return result end f100 = fib2(100) -- call it print (f100) -- write the result [/code]
Log message
Human?
public snippets
This is a community-maintained collection of reusable code snippets.
Contribute something
without logging in, or improve existing contributions. All code is dedicated to the public domain unless otherwise specified.
stats
/
top contributers