Module:Sandbox/Pelagic/01

-- Baby steps with Scribunto and Lua

-- Things I'm unsure of or probably doing wrong:  could I use subpages like Module:Pelagic/Test01 ?
 * Convention for per-user collections of modules,
 * Haven't read the coding conventions yet.
 * Caps? camelCase? underscores?
 * Existing general utility modules? (as opposed to template-specific modules)

-- Annoyances: it would be nice to have a button to comment/uncomment a line.   can't be used to fine-position cursor.
 * iOS keyboard automatically converts - - to —,
 * Hardware keyboard on iOS types curly quotes not straight quotes.
 * Tap and drag on a touchscreen selects characters and

-- Nice features: automatically outdents when you type "end".
 * Editor starts next line at same indent level,

local p = {} -- initialize a table to hold the functions

function p.create_deck(from_number, to_number) local ranks = { 'A', '2', '3', '4', '5', '6', '7', '8', '9', '10', 'J', 'Q', 'K', 'A' } -- sequence (array) of rank strings local suits = { '♥', '♦', '♠', '♣' } -- same for suits local specials = { 'joker', 'joker' } -- two jokers local d = { } -- the deck -- mw.logObject(ranks) -- mw.log(table.concat(ranks,"")) -- default to a standard 52-card deck, aces low local a = from_number or 1 local b = to_number or 13 local step = 1 if b == 14 and a == 1 then a = 2 end -- don't double up on aces if b < a then step = -1 end

for r = a, b, step do		for s = 1, 4 do c = ranks[r] .. suits[s] -- concat rank+suit -- mw.log(c) -- I was going to implement thedeck as a set -- d[c] = true -- insert the card in the deck -- but choosing a random card to draw was hard table.insert(d, c)		end end -- mw.logObject(d) mw.log(table.concat(d,',')) -- This doesn't work with a set, -- even if I set the strings as values. -- Looks like concat only works with sequences. return d end -- to-do: pass custom rank and suit and specials as params, pass params for start and end ranks function p.create_deck_doc return 	create_deck makes a deck of cards as a Lua sequence.	from_number and to_number can be in the range 1 (low ace) to 14 (high ace). end

function p.draw_card(deck) -- n = math.random(# deck) -- mw.log(n) -- c = table.remove(deck, n)	-- mw.log(c) -- return c	return table.remove(deck, math.random(# deck)) end

function p.draw_cards(deck, count) local cards = {} for i = 1, count do		table.insert(cards,p.draw_card(deck)) end return cards end

function p.hand(number) math.randomseed(os.time) local d = p.create_deck return p.draw_cards(d, number) end

function p.hand_of_cards(frame) a=frame.args number = a["number"] or a[1] list_separator = a["list_separator"] return table.concat(p.hand(number), list_separator or ' ') end

return p -- export the table