11 Replies - 9694 Views - Last Post: 23 August 2011 - 05:46 AM

#1 macosxnerd101  Icon User is online

  • Self-Trained Economist
  • member icon




Reputation: 10567
  • View blog
  • Posts: 39,120
  • Joined: 27-December 08

Week #48- Lua

Post icon  Posted 27 December 2010 - 06:24 PM

This week's challenge is Lua. Thanks to ishkabible for submitting this challenge!

Getting Started with Lua

Posted Image

Lua is an extremely simple scripting language known for it's speed. no it's not c++ but as far as dynamically typed languages go it pretty well takes the cake.
Lua is well known in the gaming industry and has been used in many games. it has been used in major games including some of my favorites Crysis and Elder Scrolls IV: Oblivion. Lua is capable of OO via what are known as meta methods. it's an extremely interesting language and is definitely worth a look. also one of the big reasons it's used in so many games is becuase of how easily you can embed it in your own applications.

IDEAS:
* write a program that prints it's own source code, this is known as a quine
* write a sorting algorithm
* write a linked list class (this one is a little tricky as Lua provides no direct means of making classes)
* write a program to find the nth highest prime number
* make a simple Lua embedded application in c/c++ that exposes a function to Lua

print("hello world")
print("5+5=" .. 5+5)
MyTable = {ishka="bible"}
for first,second in pairs(MyTable) do
	if first=="ishka" and second=="bible" then
		print(first.." + "..second,"=",first..second)
	end
end
for i=0,10,1 do
	print(i)
end
i=10
while i~=0 do
	i=i-1
	print(i)
end
function Foo()
	local MyStr = "see how easy Lua can be!!"
	print(MyStr)
end

Foo()



RESOURCES (mostly on embedding, the first one is on the language it'self):
http://lua-users.org...torialDirectory
http://www.codeproje...p/luaincpp.aspx
http://cc.byexamples...ed-lua-51-in-c/
http://gamedevgeek.c...arted-with-lua/


you can download the latest version here or here

Is This A Good Question/Topic? 1
  • +

Replies To: Week #48- Lua

#2 biggerB  Icon User is offline

  • If at first you donít succeed, call it version 1.0
  • member icon

Reputation: 80
  • View blog
  • Posts: 760
  • Joined: 11-June 10

Re: Week #48- Lua

Posted 28 December 2010 - 05:16 AM

Cool.. Looks Like a Basic type Language.. I'll Definitely Try this..
Was This Post Helpful? 0
  • +
  • -

#3 KYA  Icon User is offline

  • g++ jameson.cpp -o beverage
  • member icon

Reputation: 3101
  • View blog
  • Posts: 19,141
  • Joined: 14-September 07

Re: Week #48- Lua

Posted 28 December 2010 - 06:39 AM

Hey-o we have quite a few Lua tutorials here on site [shameless plug alert!]

Intro to Lua
Part II
Part III
Part IV

Advanced Lua
Part II
Part III



Here's a snippet that prints its own source, showing two different ways to read in a textfile:

--Week 48
--a program that prints its own source
--two different ways
filename = "ReadMe.lua"
file = assert(io.open(filename, "r"))



allOfIt = file:read("*all") --store it all
print("This lua file: \n"..allOfIt)


--reset and do it line by line
file:seek("set")
line = file:read("*line")

while true do
	line = file:read("*line")
	if(line == nil) then break end
	print(line)
end


Was This Post Helpful? 0
  • +
  • -

#4 stayscrisp  Icon User is offline

  • フカユ
  • member icon

Reputation: 999
  • View blog
  • Posts: 4,177
  • Joined: 14-February 08

Re: Week #48- Lua

Posted 28 December 2010 - 06:50 AM

I'm gonna attempt this challenge. I have been using Lua as a game scripting language and have a nice wrapper for it ;)
Was This Post Helpful? 0
  • +
  • -

#5 Sergio Tapia  Icon User is offline

  • D.I.C Lover
  • member icon

Reputation: 1253
  • View blog
  • Posts: 4,168
  • Joined: 27-January 10

Re: Week #48- Lua

Posted 28 December 2010 - 07:06 AM

I remember when I was a wee 17 year old (first year of college), my brother and I had to code in LUA for creating spells for out private Tibia server. Good times! The language itself is very easy to understand.
Was This Post Helpful? 0
  • +
  • -

#6 KYA  Icon User is offline

  • g++ jameson.cpp -o beverage
  • member icon

Reputation: 3101
  • View blog
  • Posts: 19,141
  • Joined: 14-September 07

Re: Week #48- Lua

Posted 28 December 2010 - 08:34 AM

After reviewing my incredibly weak linked list in the snippet section, I now present to you a LinkedList "class" in Lua:

--Writing a data structure in Lua
--Week 48

LinkedList = {}
function LinkedList:create(val)
	local root = { value = val,  next = nil}
	--[[
		this allows us to call LinkedList functions
		from our instantiated object [which is really a table]
	]]--
	setmetatable(root, {__index = LinkedList})
	return root
end

--self refers to the object/caller
--in our case, the initial or "root" node
function LinkedList:append(val)
	local node = { value = val, next = nil}
	--empty list
	if(self.value == nil) then
		--print("Head node is nil ")
		self.value = node.value
		self.next = node.next
		return
	end
	local curNode = self
	while curNode.next ~= nil do
		curNode = curNode.next
	end
	curNode.next = node
	return
end

function LinkedList:displayList()
	--print("Root node in displayList(): "..self.value)
	local curNode = self
	if(self.value == nil) then
		print ("List is empty!")
		return
	end
	while curNode ~= nil do
		print(curNode.value)
		curNode = curNode.next
	end
end

function LinkedList:removeNode(val)
	if type(val) == "table" then
		print("Error! Must pass a non-table to search for.")
	end
	local curNode = self
	--head/root node is the value
	if(self.value == val) then
		--print("Removing head node: "..self.value)
		local temp = self.next
		if temp ~= nil then
			self.value = temp.value
			self.next = temp.next
		else
			self.value = nil
			self.next = nil
		end
		--print("New head node: "..self.value)
		return
	end
	lastVisited = curNode
	while curNode ~= nil do
		if curNode.value == val then
			--print(val.." found!")
			--print("last visited: "..lastVisited.value.." curNode: "..curNode.value)
			lastVisited.next = curNode.next
			curNode = nil
			return
		end
		lastVisited = curNode
		curNode = curNode.next
	end
	return
end

--sample usage
test = LinkedList:create("Bob")
test:append("Knowles")
test:append("Julie")
test:displayList()
print()
test:removeNode("Knowles")
test:displayList()
print()
test:append("Joy")
test:displayList()
print()
test:append("Joy")
test:displayList()
print()
test:removeNode("Joy")
test:displayList()
print()
test:append(5)
test:displayList()
print()





Pretty sure I ironed all the bugs out. Completely forgot about Lua table scope for a brief moment. Heh.
Was This Post Helpful? 0
  • +
  • -

#7 ShaneK  Icon User is offline

  • require_once("brain.php"); //Fatal error :/
  • member icon

Reputation: 240
  • View blog
  • Posts: 1,224
  • Joined: 10-May 09

Re: Week #48- Lua

Posted 28 December 2010 - 09:36 AM

View PostSergio Tapia, on 28 December 2010 - 07:06 AM, said:

I remember when I was a wee 17 year old (first year of college), my brother and I had to code in LUA for creating spells for out private Tibia server. Good times! The language itself is very easy to understand.


You played Tibia/OTS? Hey, so did I! And I hosted a couple servers too! Using LUA to create spells and basic scripts for the server to do stuff without having to recompile the server was actually pretty nice.

Yours,
Shane~
Was This Post Helpful? 0
  • +
  • -

#8 Raynes  Icon User is offline

  • D.I.C Lover
  • member icon

Reputation: 611
  • View blog
  • Posts: 2,815
  • Joined: 05-January 09

Re: Week #48- Lua

Posted 29 December 2010 - 08:09 AM

Cute. I was playing Tibia earlier today.
Was This Post Helpful? 0
  • +
  • -

#9 KYA  Icon User is offline

  • g++ jameson.cpp -o beverage
  • member icon

Reputation: 3101
  • View blog
  • Posts: 19,141
  • Joined: 14-September 07

Re: Week #48- Lua

Posted 30 December 2010 - 07:54 AM

A Queue in Lua!

--[[
12-30-10
KYA
Queue ADT

Keeps the Lua convention of indexes starting
at 1 rather then zero


In our internal table, we keep the number of elements
stored at "curIndex".
]]--


Queue = {}
function Queue:new()
	local storage = {}
	storage["curIndex"] = 1
	setmetatable(storage, {__index = Queue})
	return storage
end

function Queue:enqueue(val)
	curIndex = self["curIndex"]
	self[curIndex] = val
	curIndex = curIndex + 1
	self["curIndex"] = curIndex
	return
end

function Queue:dequeue()
	--pop and rotate "up"
	i = 1
	if #self == 0 then
		print("Queue is empty!")
		return
	end
	--print("table size: "..#self)
	temp = self[1]
	--print("temp val: "..temp)

	--[[
	iterate from the top, swapping elements
	set the last known position to nil, erasing it
	]]--
	while i < #self do
		self[i+1], self[i] = self[i], self[i+1]
		i = i + 1
	end
	self[#self] = nil
	curIndex = self["curIndex"] - 1
	self["curIndex"] = curIndex
	return temp
end

--useful for seeing table contents when
--unexpected behavior occurs
function Queue:debugPrint()
	for i, v in ipairs(self) do
	print(i.." "..v)
	end
end

function Queue:hasMoreElements()
	if #self == 0 then
		return false
	else
		return true
	end
end

--let's look at, but not remove
function Queue:peek()
	return self[1]
end

----------------------------------------------
--IMPLEMENTATION EXAMPLE
----------------------------------------------

test = Queue:new()
test:enqueue(5)
test:enqueue("fifty")
test:enqueue("fourty")
test:enqueue(46)
test:enqueue(69)
test:enqueue('a')

--returns 5
print(test:peek())

--pop them all off, FIFO!
while test:hasMoreElements() do
	--[[
		5
		fifty
		fourty
		46
		69
		a
	]]--
	print(test:dequeue())
end

--returns nil [i.e. queue is empty]
print(test:peek())

--if you wanted to do it piecemeal
--[[
print(test:dequeue())
print(test:dequeue())
print(test:dequeue())
print(test:dequeue())
print(test:dequeue())]]--

-- illustrates that our Queue could be
-- traversed like a traditional array
--test:debugPrint()



Was This Post Helpful? 0
  • +
  • -

#10 KYA  Icon User is offline

  • g++ jameson.cpp -o beverage
  • member icon

Reputation: 3101
  • View blog
  • Posts: 19,141
  • Joined: 14-September 07

Re: Week #48- Lua

Posted 30 December 2010 - 11:31 AM

HashMaps!

--[[
12-30-10
KYA
HashMap ADT

Tables in Lua are essentially hashmaps already
This is more of a wrapper then anything
]]--

HashMap = {}
function HashMap:new()
	local storage = {}
	setmetatable(storage, {__index = HashMap})
	return storage
end

function HashMap:put(key, val)
	if self:contains(key) then
		print("Error, key already in map!")
		return
	end

	self[key] = val
end

function HashMap:contains(key)
	return self[key] ~= nil
end

function HashMap:get(key)
	return self[key]
end

---------------------------------------
--SAMPLE IMPLEMENTATION
---------------------------------------
test = HashMap:new()
test:put("Banana", 5)
test:put("LOL", 67)
test:put(5, "WTF")

print(test:get(5))				--> "WTF"
print(test:get(6))				--> nil
print(test:get("Banana"))		-->5

--iterating over key, value pairs
--pairs is a native Lua function
for k, v in pairs(test) do
	print(k.." "..v)
end

Was This Post Helpful? 0
  • +
  • -

#11 baavgai  Icon User is offline

  • Dreaming Coder
  • member icon

Reputation: 5832
  • View blog
  • Posts: 12,684
  • Joined: 16-October 07

Re: Week #48- Lua

Posted 05 January 2011 - 01:00 PM

I've always liked Lua. Ever since I power leveled that warlock, before they nerfed it... :P

Lua is a lot like Javascript meets BASIC syntax with good line continue. It's core is the associative array (table) and combined with first-class functions makes it a very flexible beastie. It doesn't have objects, but has a self reference call syntax that can amount to the same thing.

My person challenge is to write tic-tac-toe in all the challenges I haven't done yet. I had fun with it in basic and realized it's a pretty good language test case.

Here I've used the two common OO style Lua conventions. Along with a lot of function references and nesting. For some reason, I really like scoping local functions.

#!/usr/bin/env lua

Player = { None=0, X=1, O=2 }

function getBoard()
	local function show(board)
		local function cellValue(i)
			if board.cell[i]==Player.X then return "X" end
			if board.cell[i]==Player.O then return "O" end
			return string.format("%d", i)
		end
		
		local i = 1
		for row = 1,3 do
			local s = ""
			for col = 1,3 do
				s = s .. " " .. cellValue(i) .. " "
				if not (col==3) then s = s .. ":" end
				i = i + 1
			end
			print(s)
			if not (row==3) then print("---+---+---") end
		end
		print()
	end

	local function isWin(board, player)
		local function isWinRow(row)
			for i = 1, #row do
				if not (board.cell[row[i]]==player) then return false end
			end
			return true
		end
		local rows = { 
			{1,2,3}, {4,5,6}, {7,8,9},
			{1,4,7}, {2,5,8}, {3,6,9},
			{1,5,9}, {3,5,7}, 
		}
		for i = 1, #rows do if isWinRow(rows[i]) then return true end end
		return false
	end
	
	return { 
		cell = {0,0,0,0,0,0,0,0,0},
		show = function(self) show(self) end,
		get = function(self, pos) return self.cell[pos] end,
		set = function(self, pos, value) self.cell[pos]=value end,
		isWin = function(self, player) return isWin(self, player) end,
	}
end

Game = {}

function Game:new()
	local obj = { 
		MAX_TURNS = 9,
		turn = 1, isDone = false, winner = Player.None,
		board = getBoard(),
		get = function(self, pos) return self.board:get(pos) end,
		set = function(self, pos, value) return self.board:set(pos,value) end,
		isWin = function(self, player) return self.board:isWin(player) end,
	}
	
	setmetatable(obj, { __index = Game })  -- Inheritance, sort of
	return obj
end

function Game:getCurrentPlayer()
	if self.turn % 2 == 0 then return Player.O end
	return Player.X
end

function Game:show() 
	self.board:show()
	if self.isDone then
		if self.winner==Player.X then
			print "Player wins."
		elseif self.winner==Player.O then
			print "Computer wins."
		else
			print "Tie game."
		end
	else
		if self:getCurrentPlayer()==Player.X then p="X" else p="O" end
		print(string.format("Move %d, player %s.", self.turn, p))
	end
	print()
end

function Game:isOpen( pos)
	if pos<1 or pos>9 then return false end
	return self:get(pos)==Player.None
end


function Game:move(pos)
	if self.isDone or not self:isOpen(pos) then return false end
	p = self:getCurrentPlayer()
	self:set(pos, p)
	if self:isWin(p) then
		self.isDone = true
		self.winner = p
	else
		self.turn = self.turn + 1
		self.isDone = not (self.turn <= self.MAX_TURNS)
	end
	return true
end

function Game:getRandomMove()
	local openCells = self.MAX_TURNS-(self.turn-1)
	local pos = math.floor(math.random()*openCells)
	for i = 1,9 do
		if self:get(i)==Player.None then
			if pos==0 then return i end
			pos = pos - 1
		end
	end
end

function Game:getBestMove()
	local function findWin(board, player)
		for i = 1,9 do
			if board:get(i)==Player.None then
				board:set(i,player)
				local win = board:isWin(player)
				board:set(i,Player.None)
				if win then return i end
			end
		end
		return -1
	end
	player = self:getCurrentPlayer()
	pos = findWin(self.board, player)
	if pos==-1 then 
		if player==Player.X then player=Player.O else player=Player.X end
		pos = findWin(self.board, player)
		if pos==-1 then
			pos = self:getRandomMove() 
		end
	end
	return pos
end


function play(choosePlayer1func, choosePlayer2func)
	local function getMove(game)
		if game:getCurrentPlayer()==Player.X then
			return choosePlayer1func(game)
		else 
			return choosePlayer2func(game)
		end
	end
	
	game = Game:new()
	while not game.isDone do
		game:show()
		game:move(getMove(game))
	end
	game:show()
end


function test()
	local function func1(game) return game:getRandomMove() end
	local function func2(game) return game:getBestMove() end
	play(func1, func2)
end

function playInteractive()
	local function func1(game)
		while true do
			print("Enter valid position:")
			pos = tonumber(io.read())
			if not (pos==nil) and game:isOpen(pos) then return pos end
			print("Invalid choice")
		end
	end
	local function func2(game) return game:getBestMove() end
	play(func1, func2)
end


math.randomseed( os.time() )
-- test()
playInteractive()


Was This Post Helpful? 0
  • +
  • -

#12 hulla  Icon User is offline

  • Writing Lines


Reputation: 49
  • View blog
  • Posts: 732
  • Joined: 05-March 11

Re: Week #48- Lua

Posted 23 August 2011 - 05:46 AM

Hahaha I remember when I used to play Roblox, you could script in Roblox. That's where I got into programming. :) I have a soft-spot for Lua.
Was This Post Helpful? 0
  • +
  • -

Page 1 of 1