这两个Lua示例有什么区别?哪个更好?

我刚开始学习 Lua。在我学习的例子中(Ghosts&Monsters Corona开源),我一遍又一遍地看到这个模式。

local director = require("director")

local mainGroup = display.newGroup()

local function main()

   mainGroup:insert(director.directorView)

   openfeint = require ("openfeint")
   openfeint.init( "App Key Here", "App Secret Here", "Ghosts vs. Monsters", "App ID Here" )

   director:changeScene( "loadmainmenu" )

   return true
end

main()

这是有经验的 Lua 程序员推荐的某种约定吗?还是使用这种方式有真正的优势呢?为什么不跳过这个函数,直接这样做:

local director = require("director")

local mainGroup = display.newGroup()

mainGroup:insert(director.directorView)

local openfeint = require ("openfeint")
openfeint.init( "App Key Here", "App Secret Here", "Ghosts vs. Monsters", "App ID Here" )

director:changeScene( "loadmainmenu" )

第一种风格比第二种风格有一些隐含的好处吗?谢谢!

原文链接 https://stackoverflow.com/questions/4419353

点赞
stackoverflow用户4323
stackoverflow用户4323

我认为你展示的第一种风格并不是很有意义。但是,如果在底部添加类似于if arg then main() end的语句,这个脚本可能会(可能会)作为可加载的“库”而有用,除了作为一个独立的脚本。话虽如此,像这样有一个main()函数更像是C而不是Lua,所以我认为你怀疑它是对的。

2010-12-12 04:42:09
stackoverflow用户156521
stackoverflow用户156521

我经常以这种方式编写自己的 Lua 脚本,因为在这种情况下可以提高可读性:

function main()
    helper1( helper2( arg[1] ) )
    helper3()
end

function helper1( foo )
    print( foo )
end

function helper2( bar )
    return bar*bar
end

function helper3()
    print( 'hello world!' )
end

main()

这样,"main" 代码位于顶部,但我仍然可以在它执行之前定义必要的全局函数。

一个简单的技巧,真的。除了可读性之外,我想不出任何理由这样做。

2010-12-17 05:17:43
stackoverflow用户293982
stackoverflow用户293982

第一种风格可以用来提高可读性,但我更喜欢给函数一些有意义的名称,而不是 main 或者不使用函数。

顺便说一下,我认为给代码块命名,即将它们放入函数或方法中,始终是一个好的实践。它有助于解释代码的意图,并鼓励重复使用。

2010-12-26 15:40:04