LoginSignup
4
5

More than 5 years have passed since last update.

luaの基本

Last updated at Posted at 2017-03-11

rubyやpythonなどのスクリプト言語を知ってる人はわかりやすい。

大文字小文字を区別する言語。

予約語

and       break     do        else      elseif
end       false     for       function  if
in        local     nil       not       or
repeat    return    then      true      until     while

コメント

-- コメント部分

--[[
コメント部分
]]

変数

数値型

x = 10
x = 1.0
x = 10e-1

文字型

s = "aaa"
s = 'aaa'

論理型

b = true
b = false

テーブル型(配列)

table = {}
table["str"] = "Lua"
table["no"] = 1
table["bool"] = true
for i, ver in pairs(table) do
    print(ver)

演算子

算術演算子

 a % b == a - math.floor(a/b)*b

関係演算子

演算子 ~= は正確に等価 (==) の否定

==    ~=    <     >     <=    >=

論理演算子

 and   or    not

       10 or 20            --> 10
       10 or error()       --> 10
       nil or "a"          --> "a"
       nil and 10          --> nil
       false and error()   --> false
       false and nil       --> false
       false or nil        --> nil
       10 and 20           --> 20

連結演算子

str = "hoge" .. "hoge"

制御構造

if文

switch文はない。

if 式 then 
    処理1
elseif 式2 then
    処理2
else
    処理2
end

for文

for i=0, 4, 1 do  --1は増加量
    print(i)
end

while文

while 式 do 
    処理
end

repeat文

repeat 
    処理 
until 式

break文

do
    break
end

関数

function 関数名(引数1, 引数2, ..)
    関数の処理
    return 戻り値1, 戻り値2, 戻り値3
end
ver1, ver2, ver3 = func(n)

可変引数

... (コロン三つ)を指定して複数の可変にできる。

function 関数名(...)
  t = { ... }
end

無名関数

変数 = function(引数)
    処理
end

require

-- test.lua
function hoge()
  print("hoge")
end
-- main.lua
require("test")
hoge()

オブジェクト

-- オブジェクトを作成
Dog = {
  name = "Jiro",
  age  = 3,
  showProfile = function(self)
    prof = string.format("name=%s,age=%d", self.name, self.age)
    print(prof)
  end
}
-- showProfile メソッドを呼ぶ
Dog:showProfile()

継承

setmetatableの__indexにAnimalを指定して継承。

-- 基本となる Animal クラスを定義
Animal = {}
Animal.name = "unknown"
Animal.showProfile = function(self)
  print("*** profile")
  print("name="..self.name)
end
-- Animal を継承して Dog クラスを作る
Dog = {}
Dog.new = function (name)
  local obj = {}
  obj.name = name
  setmetatable(obj,{__index=Animal})
  return obj
end
-- インスタンスを生成する
jiro = Dog.new("jiro")
jiro:showProfile()

時間を計測する

仮想マシンの場合あまりよくない結果になった。
osのcpuクロック時間から求めるためおかしくなってる可能性がある。

local t1 = os.clock();

処理

local e1 = os.clock() - t1;
print("elapsedTime1 : ", e1);

時間を計測する(仮装マシン)

時間を引き算する。

local socket=require'socket'
print( socket.gettime() )
処理
print( socket.gettime() )

参考

http://starcode.web.fc2.com/
http://hyperpolyglot.org/scripting
http://www.hakkaku.net/articles/20081118-286

4
5
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
4
5