1. ホーム
  2. スクリプト・コラム
  3. ルア

Luaにおける変数と代入方法

2022-01-05 01:57:22

以下の例をご覧ください。

test.lua

-- First lua script
--comments use the "--" character
--variables are not defined, the default initialized value is nil
--such a definition is global
num1 = 1 ;
-- Adding the keyword local means that the variable is local
local num2 = 2 ;
--define the end of the variable without the semicolon; it is also possible, personal advice, because Lua is written in C, write the semicolon or standardize it
num3 = 3 
--define a function that aims to add two numbers and return
function add()
 --a = 1 can also be defined inside the function
 --b = 2 
 return num1+num2 ;
 end 
--implement a sub function that can be passed as a reference
function sub(a , b)
 return a-b ;
 end
--implement a function with multiple return values
function manyarg(a , b , c)
 return a,b,c 
 end 
--Lua's assignment operations 
x = 100 
y = 200 
-- This is equivalent to j = 10,k = 2*x
j,k = 10,2*x
--such an assignment is interpreted by Lua as swapping the values of x and y
x,y = y,x
---Receiving the return value of a function with multiple values
-- call manyarg this function will return q,w,e three arguments
-- where a gives q, b gives w, and c gives e
q,w,e = manyarg(1,2,3)
--index
--actually similar to an array of strings
_able = {}
_able["key"] = "hello"
_able1 = "Hello world!"
-- function calls 
print(add()) 
print(sub(2,1))
print(x,y)
print(q,w,e)
print(_able["key"])
print(_able.key)
print(_able1)

luaを使ったスクリプトのパース。

lua test.lua

実行結果。

3
1
200 100
1 2 3
こんにちわ
こんにちわ
Hello world!

概要

この記事の内容が、あなたの勉強や仕事の参考になれば幸いです。また、スクリプトハウスを応援していただきありがとうございます。もっと詳しく知りたい方は、以下のリンク先をご覧ください。