3

これがばかげた質問ではないことを願っていますが、これに出くわした後、私は周りを検索してきましたが、これが文書化されている場所を見つけることができません. ステートメントでのコンマ ( ,)の使用は何ですか。print()入力間をタブで連結しているようです。

例:

print("this" .. "is" .. "string" .. "concatenation");
print("how", "is", "this", "also", "working?");

出力:

thisisstringconcatenation 

how is  this    also    working?

私がわざわざこれを調査する理由は、nil値の連結を許可しているように見えるからです。

例 2:

local nilValues = nil;

print("This", "somehow", "seems", "to", "concatenate", nilValues);
print("This" .. "will" .. "crash" .. "on" .. nilValues); -- ERROR -> attempt to concatenate local 'nilValues' (a nil value)

出力 2:

This    somehow seems   to  concatenate nil

Error: lua: test.lua:7: attempt to concatenate local 'nilValues' (a nil
value)

文字列連結でのカンマの使用法を検索しようとしましたprint()が、Lua ガイドのドキュメントも調べましたが、これを説明するものは見つかりません。

4

2 に答える 2

4

print可変数の引数を取り、出力\tされる項目の間に挿入できます。が次のように定義されているかのように考えることができますprint(実際にはそうではありませんが、このサンプル コードはProgramming in Lua http://www.lua.org/pil/5.2.htmlから取得したものです) 。

printResult = ""

function print (...)
  for i,v in ipairs(arg) do
    printResult = printResult .. tostring(v) .. "\t"
  end
  printResult = printResult .. "\n"
end

例 2 では

local nilValues = nil;

print("This", "somehow", "seems", "to", "concatenate", nilValues);
print("This" .. "will" .. "crash" .. "on" .. nilValues);

最初printの引数は複数の引数を取り、その間に 1 つずつ出力します\tprint(nil)が有効であり、出力されることに注意してくださいnil

2 番目printの引数は、文字列である単一の引数を取ります。ただし、文字列と連結できないため、文字列引数"This" .. "will" .. "crash" .. "on" .. nilValuesは無効です。nil

于 2013-06-03T14:06:44.133 に答える
2
print("this" .. "is" .. "string" .. "concatenation");
print("how", "is", "this", "also", "working?");

最初の印刷では、パラメーターは 1 つだけです。「thisisstringconcatenation」という文字列です。最初に連結を行うため、次に print 関数に渡します。

2 番目の出力では、出力に渡す 5 つのパラメーターがあります。

local nilValues = nil;

print("This", "somehow", "seems", "to", "concatenate", nilValues);
print("This" .. "will" .. "crash" .. "on" .. nilValues);

2 番目の例では、文字列を nil 値で連結します。その後、エラーが発生します。

于 2013-06-04T11:20:24.280 に答える