Luaのお勉強#2

というよりも、c++STLのお勉強ぽくなってきた。

コード

#include <stdio.h>
#include <string>
#include <sstream>
#include <iostream>
#include <vector>

#include "lua.hpp"

int main(void)
{
	using namespace std;

	vector<string> luaScripts;
	luaScripts.push_back(
		"print('hello Lua world');"
	);
	luaScripts.push_back(
		"return 'one', 'two', 'three'"
	);

	lua_State *L = lua_open();
	luaL_openlibs(L);

	vector<string>::iterator i;
	for (i = luaScripts.begin(); i != luaScripts.end(); i++)
	{
		int ret = luaL_dostring(L, (*i).c_str());
		if (ret != 0)
		{
			ostringstream stream;
			stream << "error: " << lua_tostring(L, -1) << "\n";
			cout << stream.str() << endl;
			lua_pop(L, 1);
		}
	}

	string result1 = lua_tostring(L, 1);
	string result2 = lua_tostring(L, 2);
	string result3 = lua_tostring(L, 3);

	cout << result1 << "|" << result2 << "|" << result3 << endl;

	return 0;
}

STLvectorで動的配列を生成して、イテレータでまわしてみる。
Luaの簡単なエラー処理も付けてみた。

文字列フォーマット

STLの文字列クラスでのフォーマッティングっぽいやつは、ostringstreamというので出来るそうなのでそれもやってみた。

#include <sstream>

(中略)

		int ret = luaL_dostring(L, (*i).c_str());
		if (ret != 0)
		{
			ostringstream stream;
			stream << "error: " << lua_tostring(L, -1) << "\n";
			cout << stream.str() << endl;
			lua_pop(L, 1);
		}

今更だが、STL便利!(いまのところは)ポインタを考えなくていい。文字列操作をちまちま*charでやってたら日が暮れるところだ。なんかc++でプログラムしてる感覚がまるでない。

Luaのスタック

正直、Luaのスタックの仕組みをほとんど理解していないので

			lua_pop(L, 1);

ってのがまだなんなのかよくわかってない。勉強しなければ。

気になること

最近はJava脳になっていたので、変数の寿命というのが気になっていたんだが、C++の場合はたいして関係ないのかなー。GCじゃないし。C++の変数宣言は頭に持ってきたほうがいいのだろうか。それとも局所的なほうがいいのだろうか。調べてみよう。

追記:
http://q.hatena.ne.jp/1206246516
こんな話題があった。どうやら好みの問題っぽい。