您的位置:首页 > 编程语言 > Lua

Lua基础和Lua版飞机大战

2015-07-14 19:38 288 查看

Lua基础

Lua脚本语言简明入门教程

学习总结

变量

--局部变量和全局变量

--局部变量有local关键字标识,全局变量没有。

if condition then

for 0, 3 do

x = 3

end

end

变量的类型

--NIL, BOOLEAN, NUMBER, STRING, TABLE, FUNCTION, USERDATA, THREAD

--NIL类型只有一个值 nil,只有false和nil为bool值得false,其他不是(0)

--BOOLEAN类型有两个值, true和false, false:nil和false,0也是true

--NUMBER,Lua支持很大的number

--STRING, ‘’和“”都可以以

--STRING,支持所见即所得的字符串

a = [[ this
            is
           string
         ]]


相当于b = "this\nis\nstring\n"

--TABLE 功能很强大

这样写:
a = {"abc", 1, 1.5, "abdd"}
        那么:a[1] == "abc"     a[2] == 1
         注意下标是从1开始的,这与C语言不一样。
这样写:
     a = {"name" = "xiaoming", "age"=25}
      那么: a["name"] == "xiaoming"    a["age"] = 25
这样写:
      a = {name= "xiaoming", age=25}
      那么: a.name == "xiaoming"   a.age == 25
这样写:
a = {"abc", name="xiaoming", age = 25, "bcd", 1.5, 12}
那么:a.name == "xiaoming"   a.age == 25  a[1] == "abc"  a[2] == "bcd"
        跳过了带名字的。
这样写:
a = {"abc", {name="xiaoming", age=25}}
那么:a[2].name == "xiaoming"
嵌套定义。
       注意注意:a[2].sexy = "male"  a里并没有sexy成员,这样就会自动加一个sexy成员,相当于:a = {"abc", {name="xiaoming", age=25, sexy="male"}}
这样写:
  a = {}
a.name  = "xiaoming"
a.age = 25
        那么自动加上name和age成员。


循环

for var=1, 100 do
	print(var)
end


函数

functon max(a, b)
	if a > b then 
		return a
	else
		return b
	end
end


Table

config = {}   --创建一个新的表
config.words = "hello"
config.nem=100
config["name"]="zhang san"

--或者
config= {hello="hello lua", world="world"}
--对表进行遍历:
for key, var in pairs(config) do
	print(key, var)
end


面向对象

复制表的方式

people = {}
people.sayHi = function() --people类里面的一个方法
print("Please say hi")
end
--或者也可以这样定义
--function people.sayHi()
-- prin("people say hi")
--end

飞机大战的应用

ScenceStart场景

require "SceneMenu"

-- 创建一个Start的Scene,上面有一个菜单

function SceneStart()
	local scene = CCScene:create()
	local winSize = CCDirector:sharedDirector():getWinSize()

	-- 添加背景
	local bg = CCSprite:create("background.png")
	scene:addChild(bg)
	bg:setPosition(winSize.width/2, winSize.height/2) --没有ccp了

	-- 添加菜单
	local menuItem = CCMenuItemImage:create("btn1_normal.png", "btn1_push.png")
	local menu = CCMenu:createWithItem(menuItem);
	scene:addChild(menu)

	-- 添加菜单的处理函数
	local function StartGame()
		CCDirector:sharedDirector():replaceScene(SceneMenu())
	end

	--menuItem这样添加回调函数
	menuItem:registerScriptTapHandler(StartGame)
	
	return scene
end


Layer处理触摸事件

local function onTouchBegan(x, y)
		startPoint = {x = x, y = y}
		return true
	end

	local function onTouchMoved(x, y)
	end

	local function onTouchEnded(x, y)
		-- 首先判断是不是点击
		local dx = startPoint.x - x
		local dy = startPoint.y - y;
		local d = dx*dx+dy*dy
		if d > 25 then
			return
		end

		-- 找到点击的图片,进入游戏场景
		for i=0, 4 do
			local sprite = scrollContainer:getChildByTag(1000+i)
			local box = sprite:boundingBox()
			local ptInNode = scrollContainer:convertToNodeSpace(ccp(x, y))
			if box:containsPoint(ptInNode) then
				-- 切换场景
				CCDirector:sharedDirector():replaceScene(SceneGame(i))
				break;
			end
		end
	end

	local function onTouch(touchType, x, y)
		if touchType == "began" then
			return onTouchBegan(x, y)
		elseif touchType == "moved" then
			return onTouchMoved(x, y)
		else
			return onTouchEnded(x, y)
		end
	end

	touchLayer:registerScriptTouchHandler(onTouch)
	touchLayer:setTouchEnabled(true)


Lua中强制转换

local bullet = bullets:objectAtIndex(i)
			-- 强制转换成CCSprite
			bullet = tolua.cast(bullet, "CCSprite")


删除

-- removeFromParent在lua里没有
				bullet:removeFromParentAndCleanup(true)


随机函数

-- LUA中没有CCRANDOM_0_1
		-- local x = CCRANDOM_0_1() * (winSize.width-enemy:getContentSize().width) + enemy:getContentSize().width/2

		math.randomseed(os.time())
		local x = math.random(0, winSize.width-enemy:getContentSize().width) + enemy:getContentSize().width/2


onEnter和onExit调用

-- 注册脚本处理函数,当scene退出时,释放资源
	local function sceneEaventHandler(eventType)
		-- CCLog(eventType)
        if evetType == "exit" then
            bullets:release()
			enemys:release()
			animation:release();
        end
    end
	
		//要返回场景时,注册
    scene:registerScriptHandler(sceneEaventHandler)


lua调用C++

1:首先在.cpp里编写c++程序

//参数一定是lua_State* l,所以被lua调用的函数是全局函数不能是成员函数,因为成员函数有this指针。一定要调用成员函数的话只能是静态成员函数,因其没有this指针。
//返回值是int
int funcForLua2<span style="font-family: Arial, Helvetica, sans-serif;">(lua_State* l)</span>
{
	CCLog("funcForLua2 is called");
	//lua_tonumber  返回传入参数, 这里只是返回int型的,还有很多lua_to其他的。
	int add1 = lua_tonumber(l, 1);   //第一个参数是L, 第二个参数代表第几个传入参数。
	int add2 = lua_tonumber(l, 2);
	int total = add1 + add2;
	// 返回值
	lua_pushnumber(l, total);
	//要返回多个值再lua_pushnumber即可

	// 返回值的个数
	return 1;
}


2:注册给Lua调用

bool AppDelegate::applicationDidFinishLaunching()
{
    .............
    .............  
    lua_State *tolua_s = pStack->getLuaState();
 //注册给lua
	lua_register(tolua_s, "funcForLua2", funcForLua2);
 
    ..........
}


3:lua里就可以调用了

--调用c++程序
local total = funcForLua2()
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: